﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Linq;
using System.Threading.Tasks;
using System.Windows.Forms;
using DevExpress.XtraEditors;
using XChip_Common;
using System.Threading;
using System.IO.Ports;
using SerialPortHelperLib;
using System.IO;
using DevExpress.LookAndFeel;
using System.Text.RegularExpressions;
using XChipTool.Enties;
using System.Runtime.InteropServices;
using System.Configuration;
using DevExpress.XtraBars.Navigation;
using DevExpress.Diagram.Core.Native.Ribbon;
using BinAnalysisHelp;
using XModem.library;
using Newtonsoft.Json;
using XChipTool.Full;

namespace XChipTool
{


    public partial class XChip_Lite_Form : DevExpress.XtraBars.Ribbon.RibbonForm
    {



        #region 全局变量
        /// <summary>
        /// 创建上下文同步
        /// </summary>
        //private SynchronizationContext context;
        public uint i2cmIndex = 0; //i2c打开的设备序号
        public bool m_open = false;  //i2c设备打开标志
        public bool IsI2C = false; //是否是i2c模式
        public uint i2cid = 0; //i2cid
        private SerialPort sPortTemp;
        private bool btnbool = true;
        public static bool isSecurity = true;
        //private readonly xc128registerManager register = new xc128registerManager();
        private portconfigManager pcManager;
        //是否执行事件的标志，非人为触法，不要执行事件情况下
        private bool evenMask = false;
        private portconfig PCModel = new portconfig();
        public const int WM_DEVICECHANGE = 0x219;               //系统硬件改变发出的系统消息
        public const int DBT_CONFIGCHANGECANCELED = 0x0019;
        public const int DBT_DEVICEARRIVAL = 0x8000;            //系统检测到设备已经插入，并且已经处于可用转态
        public const int DBT_DEVICEQUERYREMOVE = 0x8001;
        public const int DBT_DEVICEQUERYREMOVEFAILED = 0x8002;
        public const int DBT_DEVICEREMOVEPENDING = 0x8003;
        public const int DBT_DEVICEREMOVECOMPLETE = 0x8004;     //系统检测到设备已经卸载或者拔出
        public const int DBT_QUERYCHANGSPECIFIC = 0x8005;
        public const int DBT_CUSTOMEVENT = 0x8006;
        public const int DBT_DEVICETYPEHANGED = 0x0007;
        public const int DBT_DEVNODES_CECONFIG = 0x0017;
        public const int DBT_CONFIGCHANGED = 0x0018;
        public const int DBT_USERDEFINED = 0xFFFF;              //用户自定义消息



        [DllImport("X64/XChipUSB_x64.dll", CallingConvention = CallingConvention.Cdecl)]
        public extern static IntPtr UsbControlInit();

        [DllImport("X64/XChipUSB_x64.dll", CallingConvention = CallingConvention.Cdecl)]
        public extern static IntPtr UsbOpenDevice();

        private static NLog.Logger logger = NLog.LogManager.GetCurrentClassLogger();

        private string USBItemIndex = string.Empty;


        protected override void WndProc(ref Message m)
        {
            try
            {
                //DriveInfo[] s = DriveInfo.GetDrives();
                if (m.Msg == WM_DEVICECHANGE)
                {
                    if (GetConfigValue("IsSerial") == "USB")
                    {
                        if (m.WParam.ToInt32() == DBT_DEVICETYPEHANGED)
                        {
                            RefreshUsb();

                            var index = USBDeviceHelp.UsbDev.FindIndex(c => c.DevicePath == USBItemIndex);
                            if (index != -1)
                            {
                                if (IntPtr.Size == 8)
                                {
                                    XChipUSB.UsbIniDevice64();
                                    XChipUSB.UsbUpdateDevice64();
                                    IsUsbOpen = XChipUSB.UsbSelectDevice64(index);
                                }
                                else
                                {
                                    XChipUSB.UsbIniDevice86();
                                    XChipUSB.UsbUpdateDevice86();
                                    IsUsbOpen = XChipUSB.UsbSelectDevice86(index);
                                }

                                SerialPortHelperLib.SerialSend.IsUsbOpen = IsUsbOpen;
                                USBSwitch();
                                var d = SerialSend.ReadRegister(0x80500000, sPortTemp);
                                var dd = SerialSend.ReadRegister(0x80500001, sPortTemp);
                                if (d != 0x51 || dd != 0x01)
                                {
                                    setShowMsg("芯片ID有误！停止请求！");
                                    IsUsbOpen = false;
                                    setButtonUsbBackColor(btnUsb, false);
                                    if (IntPtr.Size == 8)
                                    {
                                        XChipUSB.UsbUpdateDevice64();
                                        //var t = XChipUSB.UsbDestroyUSB64();
                                    }
                                    else
                                    {
                                        XChipUSB.UsbUpdateDevice86();
                                        //var t = XChipUSB.UsbDestroyUSB86();
                                    }
                                    USBDeviceHelp.UsbDev.ForEach(c =>
                                    {

                                        c.IsOpen = false;

                                    });
                                    USBSwitch();
                                    return;
                                }
                                #region 验证bin密码
                                var binH1 = SerialSend.ReadRegister(0x200018d0, sPortTemp).ToString("x2");
                                var binH2 = SerialSend.ReadRegister(0x200018d1, sPortTemp).ToString("x2");
                                var binH3 = SerialSend.ReadRegister(0x200018d2, sPortTemp).ToString("x2");
                                var binH4 = SerialSend.ReadRegister(0x200018d3, sPortTemp).ToString("x2");
                                if (SerialSend.ReadRegister(0x200018d4, sPortTemp).ToString("x2") == "00")
                                {

                                }
                                else
                                {
                                    var temp1 = Convert.ToUInt32($"{binH1}{binH2}{binH3}{binH4}", 16);
                                    var str = AppHelper.GetAppConfig("BinSecretKey");
                                    var eee = AppHelper.XorNotEncryption(str);
                                    if (eee != temp1)
                                    {
                                        IsUsbOpen = false;
                                        setButtonUsbBackColor(btnUsb, false);
                                        if (IntPtr.Size == 8)
                                        {
                                            XChipUSB.UsbUpdateDevice64();
                                            //var t = XChipUSB.UsbDestroyUSB64();
                                        }
                                        else
                                        {
                                            XChipUSB.UsbUpdateDevice86();
                                            //var t = XChipUSB.UsbDestroyUSB86();
                                        }
                                        USBDeviceHelp.UsbDev.ForEach(c =>
                                        {

                                            c.IsOpen = false;

                                        });
                                        IsUsbOpen = false;
                                        USBSwitch();
                                        DevExpress.XtraEditors.XtraMessageBox.Show("请输入正确的Bin密钥！");
                                        return;
                                    }
                                }
                                
                                #endregion
                                setButtonUsbBackColor(btnUsb, true);
                                USBDeviceHelp.UsbDev.ForEach(c => {
                                    if (c.DevicePath == USBItemIndex)
                                    {
                                        c.IsOpen = true;
                                    }
                                });
                                //btnUsb.Text = "关闭";
                                SetOpenSport();
                            }
                            else
                            {
                                IsUsbOpen = false;
                                setButtonUsbBackColor(btnUsb, false);
                                if (IntPtr.Size == 8)
                                {
                                    XChipUSB.UsbUpdateDevice64();
                                    //var t = XChipUSB.UsbDestroyUSB64();
                                }
                                else
                                {
                                    XChipUSB.UsbUpdateDevice86();
                                    //var t = XChipUSB.UsbDestroyUSB86();
                                }
                                USBDeviceHelp.UsbDev.ForEach(c => {
                                    c.IsOpen = false;
                                });
                                IsUsbOpen = false;
                                USBSwitch();
                                //btnUsb.Text = "打开";
                            }
                        }

                    }
                    else if (GetConfigValue("IsSerial") == "TVE")
                    {
                        switch (m.WParam.ToInt32())
                        {

                            case DBT_DEVICEARRIVAL://插入移动存储设备
                                {
                                    if (!sPortTemp.IsOpen)
                                    {
                                        Thread.Sleep(100);
                                        OpenCloesPort();
                                    }
                                }
                                break;
                            case DBT_DEVICEREMOVECOMPLETE://卸载移动存储设备
                                {
                                    setButtonBackColor(btnOpenPort);
                                    //if (!sPortTemp.IsOpen)
                                    //{

                                    //    btnOpenPort.Text = "打开";
                                    //}
                                }
                                break;
                            default:
                                break;
                        }

                    }


                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
            base.WndProc(ref m);
        }

        private void OpenCloesPort()
        {
            try
            {
                if (!comBoxPorts.Text.ToLower().Contains("com"))
                {
                    return;
                }
                sPortTemp.PortName = comBoxPorts.Text;
                sPortTemp.BaudRate = Convert.ToInt32(comBoxBaudRate.EditValue);
                sPortTemp.DataBits = 8;//int.Parse(comBoxDataBits.Text);
                sPortTemp.StopBits = System.IO.Ports.StopBits.One;
                sPortTemp.ReadTimeout = 1000;
                sPortTemp.WriteTimeout = 1000;
                sPortTemp.Parity = (System.IO.Ports.Parity)Enum.Parse(typeof(System.IO.Ports.Parity), "Even"); //comBoxParity.EditValue.ToString()
                sPortTemp.DtrEnable = true;
                sPortTemp.RtsEnable = true;
                sPortTemp.Close();
                sPortTemp.Open();

                if (sPortTemp.IsOpen)
                {
                    //添加串口赋值过程
                    SetOpenSport();



                    //ARM 使能
                    uint recdata = 0;
                    var d = SerialSend.ReadRegister(0x80500000, sPortTemp);
                    var dd = SerialSend.ReadRegister(0x80500001, sPortTemp);
                    if (d != 0x51 || dd != 0x01)
                    {
                        setShowMsg("芯片ID有误！停止请求！");
                        sPortTemp.Close();
                        return;
                    }
                    #region 验证bin密码
                    var binH1 = SerialSend.ReadRegister(0x200018d0, sPortTemp).ToString("x2");
                    var binH2 = SerialSend.ReadRegister(0x200018d1, sPortTemp).ToString("x2");
                    var binH3 = SerialSend.ReadRegister(0x200018d2, sPortTemp).ToString("x2");
                    var binH4 = SerialSend.ReadRegister(0x200018d3, sPortTemp).ToString("x2");
                    if (SerialSend.ReadRegister(0x200018d4, sPortTemp).ToString("x2")=="00")
                    {

                    }
                    else
                    {
                        var temp1 = Convert.ToUInt32($"{binH1}{binH2}{binH3}{binH4}", 16);
                        var str = AppHelper.GetAppConfig("BinSecretKey");
                        var eee = AppHelper.XorNotEncryption(str);
                        if (eee != temp1)
                        {
                            sPortTemp.Close();
                            DevExpress.XtraEditors.XtraMessageBox.Show("请输入正确的Bin密钥！");
                            return;
                        }
                    }
                    #endregion
                    recdata = (uint)recdata & (~0x0000000fU);//bit0-bit3写0
                    //SerialSend.WriteRegister(0x21, 0x80500200, recdata, sPortTemp);

                    xChip_XModem.OpenPort(sPortTemp, comBoxBaudRate.EditValue.ToString(), comBoxPorts.Text);
                    //btnOpenPort.Text = "关闭";
                    //setButtonBackColor(Color.SeaGreen, btnOpenPort);

                    //检测isp_osd是否打开
                    SerialSend.isDebug = false;
                    uint temp = (uint)SerialSend.ReadRegister(0x80300000, sPortTemp);
                    SerialSend.isDebug = true;
                    evenMask = true;
                    check_IspOSD.Checked = (temp & 0x80) == 0x80;
                    evenMask = false;

                    #region 存下此时的波特率与串口
                    PCModel = pcManager.GetSingle(c => true);
                    if (null != PCModel)
                    {
                        portconfig model = new portconfig();
                        model.ID = PCModel.ID;
                        model.PortName = comBoxPorts.EditValue.ToString();
                        model.BaudRate = comBoxBaudRate.EditValue.ToString();

                        pcManager.Update(model);
                    }
                    else
                    {
                        portconfig model = new portconfig();
                        model.PortName = comBoxPorts.EditValue.ToString();
                        model.BaudRate = comBoxBaudRate.EditValue.ToString();

                        pcManager.Insert(model);
                    }
                    #endregion
                }
                //else
                //{
                //    //setButtonBackColor( btnOpenPort);
                //    //setButtonBackColor(Color.BlueViolet, btnOpenPort);
                //    //btnOpenPort.Text = "打开";
                //}
                setButtonBackColor(btnOpenPort);

            }
            catch (Exception ex)
            {
                setShowMsg(ex.Message.ToString());
                setButtonBackColor(btnOpenPort);
                //setButtonBackColor(Color.BlueViolet, btnOpenPort);
                sPortTemp.Close();
            }
        }


        string xc128head = string.Format("{0}\\Lib\\xc151_header", Application.StartupPath);
        string xc128setting = string.Format("{0}\\Lib\\xc151_setting", Application.StartupPath);
        string xcbin = string.Format("{0}\\Lib\\XChip_Bin", Application.StartupPath);
        //string SettingPath = $"{Application.StartupPath}\\Lib\\SettingPath";


        XChip_Lite_AE xChip_AE;
        XChip_Lite_AWB xChip_AWB;
        XChip_Lite_CMX xChip_CMX;
        XChip_Lite_DNR xChip_DNS;
        //XChip_DETAIL xChip_DETAIL;
        XChip_GAMMA xChip_GAMMA;
        XChip_SDE xChip_SDE;
        XChip_RegTable xChip_RegTable;
        XChip_LENC xChip_LENC;
        //XChip_DeriveOut xChip_DeriveOut;
        XChip_RegMapping xChip_RegMapping;
        XChip_Lite_Scene_Switch xChip_Scene_Switch;
        //XChip_SimpleUpdateIQ xChip_SimpleUpdateIQ;
        XChip_CRL xChip_CRL;
        XChip_CADJ_C xChip_CADJ;
        XChip_DNR_CAL xChip_DNR_CAL;
        XChip_DeriveNew xChip_DeriveNew;
        XChip_ToolBox xChip_ToolBox;
        XChip_Gpio xChip_Gpio;
        //XChip_CADJ_C xChip_CADJ_C;
        XChip_Lite_HDR xChip_HDR;
        XChip_Lite_Yde xChip_Reg_Yde;
        XChip_Lite_Ynr xChip_Reg_Ynr;
        XChip_Lite_Cfa xChip_Reg_Cfa;
        XChip_Lite_Snr xChip_Reg_Snr;
        XChip_Reg_FCC xChip_Reg_FCC;
        XChip_ToBin_Security xChip_ToBin_Security;
        XModemForm xChip_XModem;
        XChip_HDR_Ae xChip_HDR_Ae;
        XChip_HDR_GAMMA xChip_HDR_GAMMA;
        XChip_TveSizeReckon xChip_TveSizeReckon;
        XChip_Flash xChip_Flash;
        XChip_TopReg xChip_TopReg;


        public parameter_exportManager Pe_dal { get; set; }
        private addressregisterManager addressregisterBll { get; set; }
        private xc128registerManager RegisterDal { get; set; }
        private xc151registerManager Register151Dal { get; set; }
        private xcmainregisterManager XregitsterDal { get; set; }

        private parameter_export_patchManager Pe_patch_dal { get; set; }
        private parameter_export_sceneManager Pes_dal { get; set; }
        #endregion
        private bincurrencyManager Bincurrency_BLL { get; set; }
        private serialdataManager Serialdata_BLL { get; set; }

        /// <summary>
        /// 记录usb 是否打开的状态
        /// </summary>
        private bool IsUsbOpen { get; set; } = false;


        public XChip_Lite_Form()
        {

            //System.Diagnostics.Stopwatch stopwatch = new System.Diagnostics.Stopwatch();

            //// 开始计时
            //stopwatch.Start();



            InitializeComponent();
            //// 停止计时
            //stopwatch.Stop();

            //// 获取运行时间
            //TimeSpan elapsedTime = stopwatch.Elapsed;
            //var aa = $"运行时间：{elapsedTime}" ;
            //xChip_DeriveOut1.Pe_dal = new parameter_exportManager();
            //xChip_GAMMA1.gammaM = new gammahistoryManager();
            //xChip_RegTable2.RegisterDal = new xc128registerManager();
            //xChip_RegTable2.XregitsterDal = new xcmainregisterManager();
            //xChip_Security641.bindefault_BLL = new bindefaultManager();
            //xChip_Security641.bincurrency_BLL = new bincurrencyManager();
            //xChip_Security641.xc128_1bll = new xc151Manager();
            //xChip_Security641.serialdata_BLL = new serialdataManager();
            //xChip_Security641.control_BLL = new control_parameterManager();
            //xChip_Security641.Pe_dal = new parameter_exportManager();

            //xChip_Driving_11.bindefault_BLL = new bindefaultManager();
            //xChip_Driving_11.bincurrency_BLL = new bincurrencyManager();
            //xChip_Driving_11.xc128_1bll = new xc151Manager();
            //xChip_Driving_11.Pe_dal = new parameter_exportManager();
            //xChip_Driving_11.control_BLL = new control_parameterManager();
            //xChip_Driving_11.serialdata_BLL = new serialdataManager();

            //xChip_DeriveNew1.Pe_dal = new parameter_exportManager();
            //xChip_DeriveNew1.Pes_dal = new parameter_export_sceneManager();

            //xChip_SimpleUpdateIQ1.Pe_dal = new parameter_exportManager();   
            //xChip_CADJ1.Pe_dal = new parameter_exportManager();

            //发布正式版需要注释代码
            //xChip_CADJ_C2.SendSetClick += XChip_CADJ_C2_SendSetClick1;
        }

        #region 初始化文件
        private void XChipForm_Load(object sender, EventArgs e)
        {

            //logger.Debug("测试");
            //用于调试Bin按钮开关显示和隐藏
            if (ConfigurationManager.AppSettings["IsBin"] == "1")
            {
                BinBtn.Visibility = DevExpress.XtraBars.BarItemVisibility.Always;
            }
            else
            {
                BinBtn.Visibility = DevExpress.XtraBars.BarItemVisibility.Never;
            }

            //Task.Run(() => { AppHelper.ClearFileToPath(SettingPath, false); });
            switch (AppHelper.GetAppConfig("CutFun"))
            {
                case "0":

                    break;
                case "1":
                    barButtonItem21.Visibility = DevExpress.XtraBars.BarItemVisibility.Never;
                    break;
                case "2":
                    barButtonItem24.Visibility = DevExpress.XtraBars.BarItemVisibility.Never;
                    //barButtonItem23.Visibility = DevExpress.XtraBars.BarItemVisibility.Never;
                    break;
                default:
                    break;
            }

            #region 配置提示
            toolTipC.AutoPopDelay = 5000;
            toolTipC.InitialDelay = 0;
            toolTipC.ReshowDelay = 500;
            toolTipC.SetToolTip(updateIqBtn, "批量更新setting区已导入文件的IQ");
            #endregion

            //默认收起菜单
            this.ribbonControl.Minimized = false;
            #region 基本操作选项卡
            comBoxPorts.Properties.ValueMember = "ValueMember";
            comBoxPorts.Properties.DisplayMember = "DisplayMember";
            comBoxPorts.Properties.DataSource = XChip_Common.Port.GetSerialPorts();
            comBoxPorts.ItemIndex = 0;


            comBoxBaudRate.Properties.ValueMember = "ValueMember";
            comBoxBaudRate.Properties.DisplayMember = "DisplayMember";
            comBoxBaudRate.Properties.DataSource = XChip_Common.Port.GetRate();
            comBoxBaudRate.ItemIndex = 4;

            #endregion
            //if (context == null)
            //{
            //    context = SynchronizationContext.Current;
            //}
            //setButtonBackColor(Color.BlueViolet, btnOpenPort);


            SerialSend.SendSerialSendClick += SerialSend_SendSerialSendClick;

            //btn_AE.PerformClick();//初始化AE界面
            //navigationFrame.SelectedPage = page_Xmodem;
            //navigationFrame.SelectedPage = page_CADJ;
            //navigationFrame.SelectedPage = Page_Cadj_C;
            //navigationFrame.SelectedPageIndex = 0;
            PagesLoad();
            if (GetConfigValue("IsI2C") == "1")
            {
                IsI2C = true;
            }
            else
            {
                IsI2C = false;
            }
            if (GetConfigValue("IsSerial") == "USB" || GetConfigValue("IsI2C") == "1")
            {
                if (IsI2C)
                {
                    portusbBtn.ImageOptions.ImageUri.Uri = "AlignVerticalRight;Size16x16;Office2013";
                    PortControl.Hide();
                    UsbControl.Width = 0;
                    UsbControl.Hide();
                    PortControl.Width = 0;
                    I2cControl.Width = 167;
                    RefreshUsb();
                    isUsbmodeVisible(true);
                    panelControl2.Visible = false;
                    panelControl10.Visible = false;
                    btn_WirteFile.Visible = false;
                }
                else
                {
                    portusbBtn.ImageOptions.ImageUri.Uri = "AlignVerticalRight;Size16x16;Office2013";
                    PortControl.Hide();
                    PortControl.Width = 0;
                    I2cControl.Hide();
                    I2cControl.Width = 0;
                    UsbControl.Width = 167;
                    RefreshUsb();
                    isUsbmodeVisible(true);
                }
               
            }
            else
            {
                portusbBtn.ImageOptions.ImageUri.Uri = "AlignVerticalLeft;Size16x16;Office2013";
                PortControl.Show();
                PortControl.Width = 167;
                I2cControl.Hide();
                I2cControl.Width = 0;
                UsbControl.Width = 0;
                isUsbmodeVisible(false);
            }

           
            
        }
        //是否是USB模式
        private void isUsbmodeVisible(bool isbool)
        {
            if (isbool)
            {
                barButtonItem21.Visibility = DevExpress.XtraBars.BarItemVisibility.Never;
                barButtonItem15.Visibility = DevExpress.XtraBars.BarItemVisibility.Never;
                barButtonItem42.Visibility = DevExpress.XtraBars.BarItemVisibility.Never;
                barButtonItem16.Visibility = DevExpress.XtraBars.BarItemVisibility.Never;
                barButtonItem38.Visibility = DevExpress.XtraBars.BarItemVisibility.Never;
                btn_TVE_Reset.Visible = false;
                ribbonPageGroup2.Visible = false;
                Partition_check.Visible = false;
                sys_clk_txt.Visible = false;

                updateIqBtn.Visible = false;
                panelControl3.Visible = false;
                barButtonItem39.Visibility = DevExpress.XtraBars.BarItemVisibility.Never;
                groupControl3.Size = new System.Drawing.Size(groupControl3.Width, groupControl3.Size.Height-37);
            }
            else
            {
                barButtonItem21.Visibility = DevExpress.XtraBars.BarItemVisibility.Always;
                barButtonItem15.Visibility = DevExpress.XtraBars.BarItemVisibility.Always;
                barButtonItem42.Visibility = DevExpress.XtraBars.BarItemVisibility.Always;
                barButtonItem16.Visibility = DevExpress.XtraBars.BarItemVisibility.Always;
                barButtonItem38.Visibility = DevExpress.XtraBars.BarItemVisibility.Always;
                btn_TVE_Reset.Visible = true;
                ribbonPageGroup2.Visible = true;
                Partition_check.Visible = true;
                sys_clk_txt.Visible = true;

                updateIqBtn.Visible = true;
                panelControl3.Visible = true;
            }
            simpleButton17_Click(null, null);

        }
        private void PagesLoad()
        {

            sPortTemp = new SerialPort();
            //pcManager = new portconfigManager();
            Pe_dal = new parameter_exportManager();
            Pe_patch_dal = new parameter_export_patchManager();
            addressregisterBll = new addressregisterManager();
            RegisterDal = new xc128registerManager();
            Register151Dal = new xc151registerManager();
            XregitsterDal = new xcmainregisterManager();
            Pes_dal = new parameter_export_sceneManager();
            Bincurrency_BLL = new bincurrencyManager();
            Serialdata_BLL = new serialdataManager();
            pcManager = new portconfigManager();


            serialPort1 = new SerialPortHelper();
            //发送使用的串口通讯
            serialPort1.BindSerialPortDataReceivedProcessEvent(new SerialPortHelper.DelegateSerialPortDataReceivedProcessEvent(SerialPortDataReceivedProcess1));
            serialPort1.BindSerialPortErrorEvent(new SerialPortHelper.DelegateSerialPortErrorEvent(SerialPortErrorProcess));
            serialPort1.SerialReceviedTimeInterval = 10; //接收数据时间
            serialPort1.SerialReceviedTimeInterval = 1;  //发送数据时间
                                                         //serialPort1.SPort.WriteTimeout = 3000;
                                                         //serialPort1.SPort.ReadTimeout = 3000;
            serialPort2 = new SerialPortHelper();
            //接收使用的串口通讯
            serialPort2.BindSerialPortDataReceivedProcessEvent(new SerialPortHelper.DelegateSerialPortDataReceivedProcessEvent(SerialPortDataReceivedProcess2));
            serialPort2.BindSerialPortErrorEvent(new SerialPortHelper.DelegateSerialPortErrorEvent(SerialPortErrorProcess));
            serialPort2.SerialReceviedTimeInterval = 1; //接收数据时间
            serialPort2.SerialReceviedTimeInterval = 1;  //发送数据时间


            this.splashScreenManager1.ShowWaitForm();
            NavigationPage page = new NavigationPage();
            Task.Run(() => {
                AppHelper.ClearFileToPath(xc128head, true); AppHelper.ClearFileToPath(xc128setting, true); AppHelper.ClearFileToPath(xcbin, true);
                if (GetConfigValue("IsSerial") == "TVE")
                {
                    xChip_XModem = new XModemForm(sPortTemp);
                    xChip_XModem.Dock = DockStyle.Fill;
                    xChip_XModem.OpenPortButtonClick += XModemForm_OpenPortButtonClick;
                    //xChip_XModem.sPortTemp = sPortTemp;
                    page.Controls.Add(xChip_XModem);
                    page.Name = "page_XModem";
                    navigationFrame.Invoke(new Action(() => {
                        navigationFrame.Pages.Add(page);
                    }));
                    Thread.Sleep(10);
                }
                //navigationFrame.SelectedPage = page;
                page = new NavigationPage();
                xChip_AE = XChip_Lite_AE.Instance(sPortTemp, addressregisterBll);
                xChip_AE.Dock = DockStyle.Fill;
                page.Controls.Add(xChip_AE);
                page.Name = "page_AE";
                navigationFrame.Invoke(new Action(() => {
                    //去除左上角图标
                    ShowIcon = false;

                    navigationFrame.Pages.Add(page);
                    navigationFrame.SelectedPage = page;
                }));
                #region 恢复上次选择的波特率         
                PCModel = pcManager.GetSingle(c => true);
                if (null != PCModel)
                {
                    int baudNo = XChip_Common.Port.GetRate().FindIndex(c => c.ValueMember == PCModel.BaudRate);
                    if (baudNo == -1)
                    {
                        var ds = comBoxBaudRate.Properties.DataSource as List<Enties.TreeListValue>;
                        ds.Add(new Enties.TreeListValue { DisplayMember = PCModel.BaudRate, ValueMember = PCModel.BaudRate });
                        baudNo = ds.FindIndex(c => c.ValueMember == PCModel.BaudRate);
                    }
                    comBoxBaudRate.Invoke(new Action(() =>
                    {
                        comBoxBaudRate.ItemIndex = baudNo;
                    }));
                }
                #endregion
            });





            this.splashScreenManager1.CloseWaitForm();
        }



        private void SerialSend_SendSerialSendClick(string msg)
        {
            setShowMsg(msg);
        }
        #endregion
        #region 打开串口

        private void simpleButton1_Click(object sender, EventArgs e)
        {



            SerialSend.isDebug = true;
            if (null == comBoxPorts.EditValue || string.IsNullOrWhiteSpace(comBoxPorts.EditValue.ToString()))
            {
                DevExpress.XtraEditors.XtraMessageBox.Show("可用端口未选择");
                //重新刷新下端口
                comBoxPorts.Properties.ValueMember = "ValueMember";
                comBoxPorts.Properties.DisplayMember = "DisplayMember";
                comBoxPorts.Properties.DataSource = XChip_Common.Port.GetSerialPorts();
                //setButtonBackColor(Color.BlueViolet, btnOpenPort);
                return;
            }
            //string baudRateStr = comBoxBaudRate.EditValue.ToString();
            try
            {
                if (sPortTemp.IsOpen)
                {
                    sPortTemp.Close();
                    //xModemForm1.ClosePort();
                    //重新刷新下端口
                    comBoxPorts.Properties.ValueMember = "ValueMember";
                    comBoxPorts.Properties.DisplayMember = "DisplayMember";
                    comBoxPorts.Properties.DataSource = XChip_Common.Port.GetSerialPorts();
                    //setButtonBackColor(Color.BlueViolet, btnOpenPort);
                    btnOpenPort.Text = "打开";
                }
                else
                {
                    IsUsbOpen = false;
                    //对USB开关赋值
                    USBSwitch();
                    OpenCloesPort();
                }
                setButtonBackColor(btnOpenPort);
            }
            catch (Exception ex)
            {
                setShowMsg(ex.Message.ToString());
                setButtonBackColor(btnOpenPort);
                sPortTemp.Close();

            }

        }

        /// <summary>
        /// 按钮更改颜色
        /// </summary>
        /// <param name="col">颜色</param>
        /// <param name="btn">按钮</param>
        void setButtonBackColor(SimpleButton btn)
        {
            Color col;
            if (!sPortTemp.IsOpen)
            {
                col = Color.BlueViolet;
                btn.Text = "打开";
            }
            else
            {
                col = Color.SeaGreen;
                btn.Text = "关闭";

            }
            btn.LookAndFeel.Style = DevExpress.LookAndFeel.LookAndFeelStyle.UltraFlat;
            btn.LookAndFeel.UseDefaultLookAndFeel = false;
            btn.Appearance.BackColor = col;
            btn.Appearance.Options.UseBackColor = true;

        }

        void setButtonUsbBackColor(SimpleButton btn, bool isOpen = true)
        {
            //var index = usbDevice.ItemIndex;

            Color col;
            if (IsUsbOpen && isOpen)
            {
                col = Color.SeaGreen;
                btn.Text = "关闭";
            }
            else
            {
                col = Color.BlueViolet;
                btn.Text = "打开";


            }
            btn.LookAndFeel.Style = DevExpress.LookAndFeel.LookAndFeelStyle.UltraFlat;
            btn.LookAndFeel.UseDefaultLookAndFeel = false;
            btn.Appearance.BackColor = col;
            btn.Appearance.Options.UseBackColor = true;

        }
        #endregion

        private int navigationNo(string pageTitleToFind)
        {
          
            int index = -1;
            for (int i = 0; i < navigationFrame.Pages.Count; i++)
            {
                if (navigationFrame.Pages[i].Text == pageTitleToFind)
                {
                    index = i;
                    break;
                }
            }
            //if (index != -1)
            //{
            //    index;
            //}
            return index;
        }


        private void barButtonItem7_ItemClick(object sender, DevExpress.XtraBars.ItemClickEventArgs e)
        {
            if (navigationFrame.Pages.Any(c => c.Caption == "page_DeriveNew"))
            {

                navigationFrame.SelectedPage= (INavigationPage)navigationFrame.Pages.FindFirst(c => c.Caption == "page_DeriveNew");
                //xChip_DeriveNew.sPortTemp = sPortTemp;
            }
            else
            {
                this.splashScreenManager1.ShowWaitForm();
                NavigationPage page = new NavigationPage();

                xChip_DeriveNew = new XChip_DeriveNew(Pe_dal, Pes_dal);
                xChip_DeriveNew.Dock = DockStyle.Fill;
                //xChip_AWB.sPortTemp = sPortTemp;
                page.Controls.Add(xChip_DeriveNew);
                page.Name = "page_DeriveNew";
                navigationFrame.Pages.Add(page);
                navigationFrame.SelectedPage = page;
                this.splashScreenManager1.CloseWaitForm();
            }


            //SetOpenSport();
            //navigationFrame.SelectedPageIndex = 12;
            //navigationFrame.SelectedPage = page_DeriveNew;

        }

        #region 设置文本框

        public void setShowMsg(string msg)
        {
            if (chk_IsShowLog.Checked)
            {
                this.Invoke((EventHandler)(delegate
                {
                    if (memoEdit1.Text.Length > 20000)
                    {
                        memoEdit1.Text = "";
                    }
                    //追加的形式添加到文本框末端，并滚动到最后。     
                    this.memoEdit1.Text = string.Format("{0} \r\n {2} {1}", this.memoEdit1.Text, msg, "");
                    this.memoEdit1.SelectionStart = memoEdit1.Text.Length;
                    this.memoEdit1.ScrollToCaret();

                }));
            }
        }
        #endregion
        private void SetOpenSport()
        {
            if (null != xChip_AE) xChip_AE.sPortTemp = sPortTemp;
            if (null != xChip_AWB) xChip_AWB.sPortTemp = sPortTemp;
            if (null != xChip_CMX) xChip_CMX.sPortTemp = sPortTemp;
            if (null != xChip_DNS) xChip_DNS.sPortTemp = sPortTemp;
            //if (null != xChip_DETAIL) xChip_DETAIL.sPortTemp = sPortTemp;
            if (null != xChip_GAMMA) xChip_GAMMA.sPortTemp = sPortTemp;
            if (null != xChip_SDE) xChip_SDE.sPortTemp = sPortTemp;
            if (null != xChip_RegTable) xChip_RegTable.sPortTemp = sPortTemp;
            if (null != xChip_LENC) xChip_LENC.sPortTemp = sPortTemp;
            //if (null != xChip_DeriveOut) xChip_DeriveOut.sPortTemp = sPortTemp;
            if (null != xChip_Scene_Switch) xChip_Scene_Switch.sPortTemp = sPortTemp;
            //if (null != xChip_SimpleUpdateIQ) xChip_SimpleUpdateIQ.sPortTemp = sPortTemp;
            if (null != xChip_CRL) xChip_CRL.sPortTemp = sPortTemp;
            if (null != xChip_CADJ) xChip_CADJ.sPortTemp = sPortTemp;
            if (null != xChip_DNR_CAL) xChip_DNR_CAL.sPortTemp = sPortTemp;
            if (null != xChip_Gpio) xChip_Gpio.sPortTemp = sPortTemp;
            //if (null != xChip_CADJ_C) xChip_CADJ_C.sPortTemp = sPortTemp;
            if (null != xChip_HDR) xChip_HDR.sPortTemp = sPortTemp;
            if (null != xChip_Reg_Yde) xChip_Reg_Yde.sPortTemp = sPortTemp;
            if (null != xChip_Reg_Ynr) xChip_Reg_Ynr.sPortTemp = sPortTemp;
            if (null != xChip_Reg_Cfa) xChip_Reg_Cfa.sPortTemp = sPortTemp;
            if (null != xChip_Reg_Snr) xChip_Reg_Snr.sPortTemp = sPortTemp;
            if (null != xChip_Reg_FCC) xChip_Reg_FCC.sPortTemp = sPortTemp;
            if (null != xChip_ToBin_Security) xChip_ToBin_Security.sPortTemp = sPortTemp;
            if (null != xChip_XModem) { xChip_XModem.sPortTemp = sPortTemp; xChip_XModem.IsUsbOpen = IsUsbOpen; }
            if (null != xChip_TopReg) { xChip_TopReg.sPortTemp = sPortTemp; xChip_TopReg.IsUsbOpen = IsUsbOpen; }
            if (null != xChip_HDR_Ae) { xChip_HDR_Ae.sPortTemp = sPortTemp; xChip_HDR_Ae.IsUsbOpen = IsUsbOpen; }

        }



        #region 切换页面的所有方法

        private void barButtonItem1_ItemClick(object sender, DevExpress.XtraBars.ItemClickEventArgs e)
        {
            if (navigationFrame.Pages.Any(c => c.Caption == "page_GAMMA"))
            {
                //navigationFrame.SelectedPageIndex = navigationFrame.Pages.FindIndex(c => c.Caption == "page_GAMMA");
                navigationFrame.SelectedPage = (INavigationPage)navigationFrame.Pages.FindFirst(c => c.Caption == "page_GAMMA");
                xChip_GAMMA.sPortTemp = sPortTemp;
            }
            else
            {
                this.splashScreenManager1.ShowWaitForm();
                NavigationPage page = new NavigationPage();
                xChip_GAMMA = new XChip_GAMMA(sPortTemp, addressregisterBll);
                xChip_GAMMA.Dock = DockStyle.Fill;
                //xChip_GAMMA.sPortTemp = sPortTemp;
                page.Controls.Add(xChip_GAMMA);
                page.Name = "page_GAMMA";
                navigationFrame.Pages.Add(page);
                navigationFrame.SelectedPage = page;
                this.splashScreenManager1.CloseWaitForm();
            }

            //SetOpenSport();
            //this.xChip_GAMMA1.gammaM = new gammahistoryManager();
            //navigationFrame.SelectedPageIndex =5;
            //officeNavigationBar.SelectedItem = navigationBarItem6;

        }

        private void barButtonItem2_ItemClick(object sender, DevExpress.XtraBars.ItemClickEventArgs e)
        {
            if (navigationFrame.Pages.Any(c => c.Caption == "page_AWB"))
            {
                //navigationFrame.SelectedPageIndex = navigationFrame.Pages.FindIndex(c => c.Caption == "page_AWB");
                navigationFrame.SelectedPage = (INavigationPage)navigationFrame.Pages.FindFirst(c => c.Caption == "page_AWB");
                xChip_AWB.sPortTemp = sPortTemp;
            }
            else
            {
                this.splashScreenManager1.ShowWaitForm();
                NavigationPage page = new NavigationPage();
                xChip_AWB = new XChip_Lite_AWB(sPortTemp, addressregisterBll);
                xChip_AWB.Dock = DockStyle.Fill;
                //xChip_AWB.sPortTemp = sPortTemp;
                page.Controls.Add(xChip_AWB);
                page.Name = "page_AWB";
                navigationFrame.Pages.Add(page);
                navigationFrame.SelectedPage = page;
                this.splashScreenManager1.CloseWaitForm();
            }
            //SetOpenSport();
            //navigationFrame.SelectedPageIndex = 1;
            //officeNavigationBar.SelectedItem = navigationBarItem2;           
        }

        private void barButtonItem4_ItemClick(object sender, DevExpress.XtraBars.ItemClickEventArgs e)
        {
            if (navigationFrame.Pages.Any(c => c.Caption == "page_CMX"))
            {
                //navigationFrame.SelectedPageIndex = navigationFrame.Pages.FindIndex(c => c.Caption == "page_CMX");
                navigationFrame.SelectedPage = (INavigationPage)navigationFrame.Pages.FindFirst(c => c.Caption == "page_CMX");
                xChip_CMX.sPortTemp = sPortTemp;
            }
            else
            {
                this.splashScreenManager1.ShowWaitForm();
                NavigationPage page = new NavigationPage();
                xChip_CMX = new XChip_Lite_CMX(sPortTemp, addressregisterBll);
                xChip_CMX.Dock = DockStyle.Fill;
                //xChip_AWB.sPortTemp = sPortTemp;
                page.Controls.Add(xChip_CMX);
                page.Name = "page_CMX";
                navigationFrame.Pages.Add(page);
                navigationFrame.SelectedPage = page;
                this.splashScreenManager1.CloseWaitForm();
            }
            //SetOpenSport();
            //navigationFrame.SelectedPageIndex = 2;
            //officeNavigationBar.SelectedItem = navigationBarItem3;          
        }

        private void barButtonItem3_ItemClick(object sender, DevExpress.XtraBars.ItemClickEventArgs e)
        {
            if (navigationFrame.Pages.Any(c => c.Caption == "page_DNR"))
            {
                //navigationFrame.SelectedPageIndex = navigationFrame.Pages.FindIndex(c => c.Caption == "page_DNR");
                navigationFrame.SelectedPage = (INavigationPage)navigationFrame.Pages.FindFirst(c => c.Caption == "page_DNR");
                xChip_DNS.sPortTemp = sPortTemp;
            }
            else
            {
                this.splashScreenManager1.ShowWaitForm();
                NavigationPage page = new NavigationPage();
                xChip_DNS = new XChip_Lite_DNR(sPortTemp, addressregisterBll);
                xChip_DNS.Dock = DockStyle.Fill;
                xChip_DNS.sPortTemp = sPortTemp;
                page.Controls.Add(xChip_DNS);
                page.Name = "page_DNR";
                navigationFrame.Pages.Add(page);
                navigationFrame.SelectedPage = page;
                this.splashScreenManager1.CloseWaitForm();
            }
            //SetOpenSport();
            //navigationFrame.SelectedPageIndex = 3;
            //officeNavigationBar.SelectedItem = navigationBarItem4;            
        }
        private void btn_DNR_CAL_ItemClick(object sender, DevExpress.XtraBars.ItemClickEventArgs e)
        {
            if (navigationFrame.Pages.Any(c => c.Caption == "page_DNR_CAL"))
            {
                //navigationFrame.SelectedPageIndex = navigationFrame.Pages.FindIndex(c => c.Caption == "page_DNR_CAL");
                navigationFrame.SelectedPage = (INavigationPage)navigationFrame.Pages.FindFirst(c => c.Caption == "page_DNR_CAL");
                xChip_DNR_CAL.sPortTemp = sPortTemp;
            }
            else
            {
                this.splashScreenManager1.ShowWaitForm();
                NavigationPage page = new NavigationPage();
                xChip_DNR_CAL = new XChip_DNR_CAL(sPortTemp, addressregisterBll);
                xChip_DNR_CAL.Dock = DockStyle.Fill;
                xChip_DNR_CAL.sPortTemp = sPortTemp;
                page.Controls.Add(xChip_DNR_CAL);
                page.Name = "page_DNR_CAL";
                navigationFrame.Pages.Add(page);
                navigationFrame.SelectedPage = page;
                this.splashScreenManager1.CloseWaitForm();
            }
            //SetOpenSport();
            //navigationFrame.SelectedPage = page_DNR_CAL;       
        }

        private void barButtonItem5_ItemClick(object sender, DevExpress.XtraBars.ItemClickEventArgs e)
        {
            //SetOpenSport();
            //navigationFrame.SelectedPageIndex = 7;
            //officeNavigationBar.SelectedItem = navigationBarItem8;

        }

        private void barButtonItem9_ItemClick(object sender, DevExpress.XtraBars.ItemClickEventArgs e)
        {
            if (navigationFrame.Pages.Any(c => c.Caption == "page_SDE"))
            {
                //navigationFrame.SelectedPageIndex = navigationFrame.Pages.FindIndex(c => c.Caption == "page_SDE");
                navigationFrame.SelectedPage = (INavigationPage)navigationFrame.Pages.FindFirst(c => c.Caption == "page_SDE");
                xChip_SDE.sPortTemp = sPortTemp;
            }
            else
            {
                this.splashScreenManager1.ShowWaitForm();
                NavigationPage page = new NavigationPage();
                xChip_SDE = new XChip_SDE(sPortTemp, addressregisterBll);
                xChip_SDE.Dock = DockStyle.Fill;
                xChip_SDE.sPortTemp = sPortTemp;
                page.Controls.Add(xChip_SDE);
                page.Name = "page_SDE";
                navigationFrame.Pages.Add(page);
                navigationFrame.SelectedPage = page;
                this.splashScreenManager1.CloseWaitForm();
            }
            //对USB开关赋值
            USBSwitch();
            //SetOpenSport();
            //navigationFrame.SelectedPageIndex = 6;
            //officeNavigationBar.SelectedItem = navigationBarItem7;          
        }




        #endregion

        private void barButtonItem10_ItemClick(object sender, DevExpress.XtraBars.ItemClickEventArgs e)
        {
            //btn_Reg

            if (navigationFrame.Pages.Any(c => c.Caption == "page_Reg"))
            {
                //navigationFrame.SelectedPageIndex = navigationFrame.Pages.FindIndex(c => c.Caption == "page_Reg");
                navigationFrame.SelectedPage = (INavigationPage)navigationFrame.Pages.FindFirst(c => c.Caption == "page_Reg");
            }
            else
            {
                this.splashScreenManager1.ShowWaitForm();
                NavigationPage page = new NavigationPage();
                xChip_RegTable = new XChip_RegTable(sPortTemp, Register151Dal);
                xChip_RegTable.Dock = DockStyle.Fill;
                page.Controls.Add(xChip_RegTable);
                page.Name = "page_Reg";
                navigationFrame.Pages.Add(page);
                navigationFrame.SelectedPage = page;
                this.splashScreenManager1.CloseWaitForm();
            }

            //SetOpenSport();
            //navigationFrame.SelectedPageIndex = 8;

        }

        private void barButtonItem14_ItemClick(object sender, DevExpress.XtraBars.ItemClickEventArgs e)
        {

            if (navigationFrame.Pages.Any(c => c.Caption == "page_AE"))
            {
                //navigationFrame.SelectedPageIndex = navigationFrame.Pages.FindIndex(c => c.Caption == "page_AE");
                navigationFrame.SelectedPage = (INavigationPage)navigationFrame.Pages.FindFirst(c => c.Caption == "page_AE");
            }
            //else {
            //    NavigationPage page = new NavigationPage();
            //    xChip_AE = new XChipTool.XChip_AE();
            //    xChip_AE.Dock = DockStyle.Fill;
            //    xChip_AE.sPortTemp = sPortTemp;
            //    page.Controls.Add(xChip_AE);
            //    page.Name = "page_AE";
            //    navigationFrame.Pages.Add(page);
            //    navigationFrame.SelectedPage = page;
            //}

        }

        private void barButtonItem13_ItemClick(object sender, DevExpress.XtraBars.ItemClickEventArgs e)
        {
            //SetOpenSport();
            //navigationFrame.SelectedPageIndex = 4;
            //officeNavigationBar.SelectedItem = navigationBarItem5;          
        }

        private void btn_ISP_Write_Click(object sender, EventArgs e)
        {
            if (GetConfigValue("IsSerial") == "TVE")
            //if (portusbBtn.ImageOptions.ImageUri.Uri.Contains("AlignVerticalLeft"))
            {


                if (!sPortTemp.IsOpen)//串口检测
                {
                    DevExpress.XtraEditors.XtraMessageBox.Show("串口未打开");
                    return;
                }
                uint reg_address = Convert.ToUInt32(textEdit1.Text.Replace(" ", ""), 16);


                uint reg_data = Convert.ToUInt32(textEdit2.Text, 16);

                SerialSend.WriteRegister(reg_address, reg_data, sPortTemp);
            }
            if (GetConfigValue("IsSerial") == "USB" || GetConfigValue("IsI2C") == "1")
            //if (portusbBtn.ImageOptions.ImageUri.Uri.Contains("AlignVerticalRight"))
            {
                if (!IsUsbOpen && !m_open)
                {
                    DevExpress.XtraEditors.XtraMessageBox.Show("USB未打开");
                    return;
                }
                uint reg_address = Convert.ToUInt32(textEdit1.Text.Replace(" ", ""), 16);


                uint reg_data = Convert.ToUInt32(textEdit2.Text, 16);
                SerialSend.WriteRegister(reg_address, reg_data, sPortTemp);
            }
        }

        private void btn_ISP_Read_Click(object sender, EventArgs e)
        {
            if (GetConfigValue("IsSerial") == "TVE")
            //if (portusbBtn.ImageOptions.ImageUri.Uri.Contains("AlignVerticalLeft"))
            {
                if (!sPortTemp.IsOpen)//串口检测
                {
                    DevExpress.XtraEditors.XtraMessageBox.Show("串口未打开");
                    return;
                }
                if (string.IsNullOrEmpty(textEdit1.Text)) { return; }
                textEdit2.Text = SerialSend.ReadRegister(Convert.ToUInt32((textEdit1.Text).Replace(" ", ""), 16), sPortTemp).ToString("X2");
            }

            if (GetConfigValue("IsSerial") == "USB" || GetConfigValue("IsI2C") == "1")
            //if (portusbBtn.ImageOptions.ImageUri.Uri.Contains("AlignVerticalRight"))
            {
                if (!IsUsbOpen && !m_open)
                {
                    DevExpress.XtraEditors.XtraMessageBox.Show("USB未打开");
                    return;
                }
                textEdit2.Text = SerialSend.ReadRegister(Convert.ToUInt32((textEdit1.Text).Replace(" ", ""), 16), sPortTemp).ToString("X2");
            }

        }
        public static UInt32 addr;//全局变量
        /// <summary>
        /// isp 文件写
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btn_WirteFile_Click(object sender, EventArgs e)
        {
            if (portusbBtn.ImageOptions.ImageUri.Uri.Contains("AlignVerticalRight"))
            {
                if (!IsUsbOpen)
                {
                    DevExpress.XtraEditors.XtraMessageBox.Show("USB未打开");
                    return;
                }
                OpenFileDialog openFileDialog = new OpenFileDialog();//将打开的地址给ofd
                openFileDialog.Filter = "TXT Files(*.txt)|*.txt|All Files(*.*)|*.*";
                if (openFileDialog.ShowDialog() == DialogResult.OK)//用户是否选择确定
                {
                    bool t;
                    if (IntPtr.Size == 8)
                    {
                        t = XChipUSB.UsbRegisterWriteFile64(openFileDialog.FileName);
                    }
                    else
                    {
                        t = XChipUSB.UsbRegisterWriteFile86(openFileDialog.FileName);
                    }
                    if (t)
                    {
                        DevExpress.XtraEditors.XtraMessageBox.Show("USB写入完成！");
                    }
                    else
                    {
                        DevExpress.XtraEditors.XtraMessageBox.Show("USB写入失败！");
                    }
                }

                return;
            }

            if (!sPortTemp.IsOpen)//串口检测
            {
                DevExpress.XtraEditors.XtraMessageBox.Show("串口未打开");
                return;
            }
            long test_value1 = (long)BaseRegisterMap.SPI_BASE_ADDR;
            uint test_value2 = (uint)SPIRegisterMap.SPI_FUNCTION_SELECT;
            uint FUNCT_SEL_ADDR = (uint)(test_value1 + test_value2);
            //Flash Mode
            FlashBase fb = new FlashBase(sPortTemp);
            fb.SendEvent += setShowMsg;
            fb.SendRegDataARM(0x1, FUNCT_SEL_ADDR, 0, sPortTemp);


            OpenFileDialog openFileDialog1 = new OpenFileDialog();//将打开的地址给ofd
            openFileDialog1.Filter = "TXT Files(*.txt)|*.txt|All Files(*.*)|*.*";
            if (openFileDialog1.ShowDialog() == DialogResult.OK)//用户是否选择确定
            {
                try
                {
                    string txt_str = String.Empty;
                    string[] ss;
                    // string line;
                    UInt32 reg_address;
                    UInt32 reg_data;
                    //UInt32 Value;
                    StreamReader f2 = new StreamReader(openFileDialog1.FileName, System.Text.Encoding.GetEncoding("gb2312"));//gb2312编码，为制定文件名初始化
                    WaitBefore.Start("文件写", "正在加载中", 60);
                    //SerialSend.isDebug = false;
                    while (f2.Peek() > -1)
                    {
                        try
                        {
                            txt_str = f2.ReadLine().Trim();
                            //ss = txt_str.Split(new char[] { ','}, StringSplitOptions.RemoveEmptyEntries);
                            if (txt_str.Contains("//"))//去除注释
                            {
                                txt_str = txt_str.Remove(txt_str.IndexOf("//"));
                            }
                            txt_str = txt_str.Replace('，', ',').Replace(" ", "");//全换成英文逗号，去掉空格
                            ss = txt_str.Split(',');
                            if (ss.Length > 2)
                            {
                                if (ss[0].Trim() == "0xfffd")
                                {
                                    addr = (Convert.ToUInt32(ss[1].Trim(), 16) & 0xff) << 24;
                                }
                                else if (ss[0].Trim() == "0xfffe")
                                {
                                    //addr = 0x80000000;                                   
                                    addr = (addr & 0xff000000) + ((Convert.ToUInt32(ss[1].Trim(), 16) & 0xff) << 16);
                                }
                                else if (ss[0].Trim() == "0xffff")
                                {
                                    uint t;
                                    t = (Convert.ToUInt32(ss[1].Trim(), 16) & 0xff);
                                    Thread.Sleep(1000);
                                }

                                else if (ss[0].Trim() == "0xf4f5")
                                {
                                    ;
                                }
                                else if (ss[0].Trim() == "0xf5f5")
                                {
                                    ;
                                }
                                else if (ss[0].Trim() == "0xf6f5")
                                {
                                    ;
                                }
                                else if (ss[0].Trim() == "0xfff3")
                                {
                                    UInt16 chip_id;
                                    reg_address = 0x80500010;
                                    reg_data = 0;
                                    fb.ReadRegData(0x11, reg_address, ref reg_data, sPortTemp);
                                    chip_id = (UInt16)(reg_data >> 16);
                                    if (chip_id != Convert.ToUInt32(ss[1].Trim(), 16))
                                    {
                                        f2.Close();//释放系统资源
                                        f2.Dispose();
                                        DevExpress.XtraEditors.XtraMessageBox.Show("Chip ID don't match, Write stopped!");
                                        //MessageBox.Show("Chip ID don't match, Write stopped!");
                                        break;
                                    }

                                }
                                else
                                {

                                    reg_address = addr + (Convert.ToUInt32(ss[0].Trim(), 16) & 0xffff);

                                    reg_data = Convert.ToUInt32(ss[1].Trim(), 16);
                                    SerialSend.WriteRegister(reg_address, reg_data, sPortTemp);

                                    Thread.Sleep(5);
                                }

                            }
                        }
                        catch (Exception ex)
                        {
                            DevExpress.XtraEditors.XtraMessageBox.Show(ex.Message);
                            //MessageBox.Show(ex.Message);
                        }
                    }
                    Application.DoEvents();
                    f2.Close();//释放系统资源
                    f2.Dispose();
                    WaitBefore.Close();
                    SerialSend.isDebug = true;
                    DevExpress.XtraEditors.XtraMessageBox.Show("完成");
                    //MessageBox.Show("完成");
                }

                catch (Exception ex)
                {
                    WaitBefore.Close();
                    SerialSend.isDebug = true;
                    DevExpress.XtraEditors.XtraMessageBox.Show(ex.Message);
                    //MessageBox.Show(ex.Message);
                }
            }
        }
        /// <summary>
        /// 参数导出
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btn_ParaExport_Click(object sender, EventArgs e)
        {

            if (!sPortTemp.IsOpen && !IsUsbOpen && !m_open)
            {
                DevExpress.XtraEditors.XtraMessageBox.Show("可用端口未打开");
                return;
            }
            XChip_ParameterExportOptions xpar = new XChip_ParameterExportOptions(sPortTemp);
            xpar.ShowDialog();
            //if (!sPortTemp.IsOpen)
            //{
            //    DevExpress.XtraEditors.XtraMessageBox.Show("可用端口未打开");
            //    return;
            //}

            //SaveFileDialog sfd = new SaveFileDialog();
            ////设置文件类型 
            //sfd.Filter = "配置文件（*.txt）|*.txt";

            ////设置默认文件类型显示顺序 
            //sfd.FilterIndex = 1;

            ////保存对话框是否记忆上次打开的目录 
            //sfd.RestoreDirectory = true;
            //sfd.FileName = "IQ_Setting_" + DateTime.Now.ToString("yyyyMMddHHmmss");
            //if (sfd.ShowDialog() == DialogResult.OK)
            //{
            //    SerialSend.isDebug = false;
            //    StringBuilder sb = new StringBuilder();
            //    sb.Append("// ");
            //    sb.Append("#region config xchip_IQ_regs =\n");
            //    sb.Append("{\n");
            //    sb.Append("//********** Step 10 IQ setting********************************//\n");
            //    //Pe_dal = new parameter_exportManager();
            //    if (null != Pe_dal)
            //    {
            //        WaitBefore.Start("参数导出", "正在加载中", 60);
            //        //var tempList = Pe_dal.GetList().OrderBy(c => c.SortNum);
            //        string sceneStr = string.Empty;
            //        string cutFun = AppHelper.GetAppConfig("CutFun");
            //        switch (cutFun)
            //        {
            //            case "0":
            //                sceneStr += "ALL";
            //                break;
            //            case "1"://安防 
            //                sceneStr += "安防";
            //                break;
            //            case "2"://车载  
            //                sceneStr += "行车";
            //                break;
            //            default:
            //                break;
            //        }
            //        if (cutFun != "0")
            //            sceneStr += (SerialSend.ReadRegister((0x80500241), sPortTemp) & 0x08) == 0x08 ? "3D" : "2D";
            //        var tempList = Pe_dal.GetListToExport(sceneStr);
            //        //var moduleList = SerialSend.ReadRegister((0x8014080b), sPortTemp) == 1?tempList.Select(c => c.Module).Distinct() : tempList.Where(c => c.Module != "3D DNS" && c.Module != "AE_LFC").Select(c => c.Module).Distinct();//[ 7: 0]Psram_Check_Status;
            //        var moduleList = tempList.Select(c => c.Module).Distinct().ToList();
            //        if (moduleList.Contains(null))
            //        {
            //            WaitBefore.Close();
            //            XtraMessageBox.Show("参数导出寄存器表中存在Module为null的寄存器,无法继续", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
            //            return;
            //        }
            //        #region 白天寄存器
            //        //var Pe_patch_dal = new parameter_export_patchManager();
            //        //var patchList = Pe_patch_dal.GetList();
            //        var conditionList = tempList.Select(c => c.ConditionAddr).Distinct();
            //        foreach (var item in conditionList)
            //        {
            //            if (SerialSend.ReadRegister(Convert.ToUInt32(item, 16), sPortTemp) == 0)
            //            {
            //                foreach (var item2 in tempList.Where(c => c.ConditionAddr == item))
            //                {
            //                    item2.RelationAddr = null;
            //                }
            //                //patchList.RemoveAll(c => c.ConditionAddr == item);
            //            }
            //        }
            //        #endregion
            //        sb.Append("//IQ_Start\n");
            //        sb.Append("0xfffd,0x80,\n");
            //        sb.Append("//10.1 IQ_common");
            //        //if (SerialSend.ReadRegister((0x8014080b), sPortTemp) == 1)//[ 7: 0]Psram_Check_Status;
            //        //{
            //        //tempList = Pe_dal.GetList().OrderBy(c => c.SortNum);

            //        foreach (var items in moduleList)
            //        {
            //            if (items.Contains("avg_size"))
            //                sb.Append("\n//10.2 IQ_oneself");
            //            sb.Append($"\n//{items}\n");
            //            foreach (var item in tempList.Where(c => c.Module == items).OrderBy(c => c.SortNum))
            //            {
            //                if (item.ReadAddr.Contains("089a"))
            //                {

            //                }
            //                try
            //                {
            //                    sb.Append(string.IsNullOrEmpty(item.PreNote) ? "" : "\n" + item.PreNote + "\n");
            //                    sb.Append(string.IsNullOrEmpty(item.addr) ? "" : item.addr);
            //                    if (!string.IsNullOrEmpty(item.ReadAddr))
            //                    {
            //                        //if (patchList.Count != 0 && patchList.Select(c => c.ReadAddr).Contains(item.ReadAddr))
            //                        if (!string.IsNullOrEmpty(item.RelationAddr))
            //                        {
            //                            var regVal = SerialSend.ReadRegister((Convert.ToUInt32(item.RelationAddr.Trim(), 16)), sPortTemp);
            //                            //bool isbit7 = !string.IsNullOrEmpty(patchList.Where(c => c.ReadAddr == item.ReadAddr).First().Bit) && patchList.Where(c => c.ReadAddr == item.ReadAddr).First().Bit == "&0x7f";
            //                            bool isbit7 = !string.IsNullOrEmpty(item.Bit) && item.Bit == "&0x7f";
            //                            sb.Append(isbit7 ? $",0x{(regVal & 0x7f).ToString("x2")}," : $",0x{regVal.ToString("x2")},");
            //                        }
            //                        else
            //                        {
            //                            sb.Append($",0x{SerialSend.ReadRegister((Convert.ToUInt32(item.ReadAddr.Trim(), 16)), sPortTemp).ToString("x2")},");
            //                        }
            //                    }
            //                    sb.Append(string.IsNullOrEmpty(item.RearNote) ? "" : item.RearNote = item.RearNote.Replace("\\n", "\n").Replace("\\r", "\r"));
            //                    sb.Append("\n");
            //                }
            //                catch (Exception ex)
            //                {
            //                    WaitBefore.Close();
            //                    setShowMsg(item.ReadAddr);
            //                    DevExpress.XtraEditors.XtraMessageBox.Show(ex.Message);
            //                    throw;
            //                }
            //            }
            //        }
            //        sb.Append("\n//IQ_End\n");
            //        sb.Append("}\n");
            //        System.IO.File.WriteAllText(sfd.FileName, sb.ToString());
            //        WaitBefore.Close();
            //        DevExpress.XtraEditors.XtraMessageBox.Show("参数导出完成");
            //    }
            //    SerialSend.isDebug = true;
            //}
        }

        /// <summary>
        /// 切换缩放
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void simpleButton1_Click_1(object sender, EventArgs e)
        {
            //backBtn.LookAndFeel.SetSkinStyle("Office 2016 Colorful");
            //Uri = 'Forward' Backward "Office 2016 Colorful"
            if (panelControl1.Size.Width == 40)
            {

                backBtn.ImageOptions.ImageUri = new DevExpress.Utils.DxImageUri("Backward;Size16x16;Office2013");

                panelControl1.Size = new System.Drawing.Size(174, panelControl1.Size.Height);

                foreach (Control item in panelControl1.Controls)
                {
                    if (item is PanelControl)
                    {
                        item.Show();
                    }
                }
            }
            else
            {
                backBtn.ImageOptions.ImageUri = new DevExpress.Utils.DxImageUri("Forward;Size16x16;Office2013");
                panelControl1.Size = new System.Drawing.Size(40, panelControl1.Size.Height);
                foreach (Control item in panelControl1.Controls)
                {
                    if (item.Name == "topControl")
                    {
                        continue;
                    }
                    if (item is PanelControl)
                    {
                        item.Hide();
                    }
                }
            }

        }

        private void barButtonItem16_ItemClick(object sender, DevExpress.XtraBars.ItemClickEventArgs e)
        {

            if (navigationFrame.Pages.Any(c => c.Caption == "page_XModem"))
            {
                xChip_XModem.sPortTemp = sPortTemp;
                xChip_XModem.IsUsbOpen = IsUsbOpen;
                //navigationFrame.SelectedPageIndex = navigationFrame.Pages.FindIndex(c => c.Caption == "page_XModem");
                navigationFrame.SelectedPage = (INavigationPage)navigationFrame.Pages.FindFirst(c => c.Caption == "page_XModem");
                xChip_XModem.CalculationCrystalOscillator();
            }
            else
            {
                xChip_XModem.IsUsbOpen = IsUsbOpen;
            }
            if (btnbool)
            {

                btnbool = false;
            }

            SetOpenSport();
            USBSwitch();
            //navigationFrame.SelectedPage = page_Xmodem;
            ////officeNavigationBar.SelectedItem = navigationBarItem11;
            //xModemForm1.SendSetXModemClick += XModemForm1_SendSetXModemClick;
            //xModemForm1.SendChangeSysClk += XModemForm1_SendChangeSysClk; ;
        }

        private void XModemForm1_SendChangeSysClk()
        {
            if (sPortTemp.IsOpen)
            {

                SerialSend.WriteRegister(0x80500021, 0x08, sPortTemp);
                //Thread.Sleep(1000);
                //xModemForm1.CalculationCrystalOscillator();
                //Thread.Sleep(1000);
            }
        }

        private void XModemForm1_SendSetXModemClick(bool isOpen)
        {
            if (isOpen)
            {
                if (sPortTemp.IsOpen)
                {
                    sPortTemp.Close();
                }

                //xModemForm1.ClosePort();
                //重新刷新下端口
                comBoxPorts.Properties.ValueMember = "ValueMember";
                comBoxPorts.Properties.DisplayMember = "DisplayMember";
                comBoxPorts.Properties.DataSource = XChip_Common.Port.GetSerialPorts();
                //setButtonBackColor(Color.BlueViolet, btnOpenPort);
                //btnOpenPort.Text = sPortTemp.IsOpen ? "关闭" : "打开";
                setButtonBackColor(btnOpenPort);
            }
        }

        private void barButtonItem17_ItemClick(object sender, DevExpress.XtraBars.ItemClickEventArgs e)
        {
            if (navigationFrame.Pages.Any(c => c.Caption == "page_LENC"))
            {
                //navigationFrame.SelectedPageIndex = navigationFrame.Pages.FindIndex(c => c.Caption == "page_LENC");
                navigationFrame.SelectedPage = (INavigationPage)navigationFrame.Pages.FindFirst(c => c.Caption == "page_LENC");
                //xChip_LENC.sPortTemp = sPortTemp;
            }
            else
            {
                this.splashScreenManager1.ShowWaitForm();
                NavigationPage page = new NavigationPage();
                xChip_LENC = new XChip_LENC(sPortTemp, addressregisterBll, Pe_patch_dal, Pe_dal);
                xChip_LENC.Dock = DockStyle.Fill;
                //xChip_LENC.sPortTemp = sPortTemp;
                page.Controls.Add(xChip_LENC);
                page.Name = "page_LENC";
                navigationFrame.Pages.Add(page);
                navigationFrame.SelectedPage = page;
                this.splashScreenManager1.CloseWaitForm();
            }
        }

        private void barButtonItem18_ItemClick(object sender, DevExpress.XtraBars.ItemClickEventArgs e)
        {
            if (navigationFrame.Pages.Any(c => c.Caption == "page_RegMapping"))
            {
                //navigationFrame.SelectedPageIndex = navigationFrame.Pages.FindIndex(c => c.Caption == "page_RegMapping");
                navigationFrame.SelectedPage = (INavigationPage)navigationFrame.Pages.FindFirst(c => c.Caption == "page_RegMapping");
                //xChip_RegMapping.sPortTemp = sPortTemp;
            }
            else
            {
                this.splashScreenManager1.ShowWaitForm();
                NavigationPage page = new NavigationPage();
                xChip_RegMapping = new XChip_RegMapping(addressregisterBll);
                xChip_RegMapping.Dock = DockStyle.Fill;
                //xChip_LENC.sPortTemp = sPortTemp;
                page.Controls.Add(xChip_RegMapping);
                page.Name = "page_RegMapping";
                navigationFrame.Pages.Add(page);
                navigationFrame.SelectedPage = page;
                this.splashScreenManager1.CloseWaitForm();
            }
            //xChip_RegMapping2.Addr_dal = new addressregisterManager();

            //navigationFrame.SelectedPageIndex = 12;
            //officeNavigationBar.SelectedItem = null;
        }

        private void simpleButton1_Click_2(object sender, EventArgs e)
        {
            memoEdit1.Text = string.Empty;
        }


        private void barButtonItem19_ItemClick(object sender, DevExpress.XtraBars.ItemClickEventArgs e)
        {
            if (navigationFrame.Pages.Any(c => c.Caption == "page_SCENE"))
            {
                //navigationFrame.SelectedPageIndex = navigationFrame.Pages.FindIndex(c => c.Caption == "page_SCENE");
                navigationFrame.SelectedPage = (INavigationPage)navigationFrame.Pages.FindFirst(c => c.Caption == "page_SCENE");
                xChip_Scene_Switch.sPortTemp = sPortTemp;
            }
            else
            {
                this.splashScreenManager1.ShowWaitForm();
                NavigationPage page = new NavigationPage();
                xChip_Scene_Switch = new XChip_Lite_Scene_Switch(sPortTemp, addressregisterBll);
                xChip_Scene_Switch.Dock = DockStyle.Fill;
                xChip_Scene_Switch.sPortTemp = sPortTemp;
                page.Controls.Add(xChip_Scene_Switch);
                page.Name = "page_SCENE";
                navigationFrame.Pages.Add(page);
                navigationFrame.SelectedPage = page;
                this.splashScreenManager1.CloseWaitForm();
            }
            //SetOpenSport();
            //navigationFrame.SelectedPageIndex = 14;
            //officeNavigationBar.SelectedItem = null;
        }

        private void simpleButton8_Click(object sender, EventArgs e)//串口检测
        {
            comBoxPorts.Properties.ValueMember = "ValueMember";
            comBoxPorts.Properties.DisplayMember = "DisplayMember";
            comBoxPorts.Properties.DataSource = XChip_Common.Port.GetSerialPorts();
            comBoxPorts.ItemIndex = 1;
        }
        /// <summary>
        /// 体统版本号
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void barButtonItem20_ItemClick(object sender, DevExpress.XtraBars.ItemClickEventArgs e)
        {
            //DevExpress.XtraEditors.XtraMessageBox.Show(System.Configuration.ConfigurationManager.AppSettings["VER"].Replace("\\r", "\r").Replace("\\n", "\n"), "Version", MessageBoxButtons.OK, MessageBoxIcon.Information);
            Version xpar = new Version();
            xpar.ShowDialog();

        }

        private void comBoxBaudRate_Leave(object sender, EventArgs e)
        {
            string _baudRate = comBoxBaudRate.Text;
            if (_baudRate.Contains("*"))//text是密文则 直接retrun
            {
                return;
            }
            var ds = comBoxBaudRate.Properties.DataSource as List<Enties.TreeListValue>;
            if (!ds.Exists(c => c.ValueMember == comBoxBaudRate.Text))
            {
                ds.Add(new Enties.TreeListValue() { DisplayMember = "*****", ValueMember = _baudRate });
                comBoxBaudRate.EditValue = _baudRate;
            }
        }
        /// <summary>
        /// 快捷工具
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void barButtonItem22_ItemClick(object sender, DevExpress.XtraBars.ItemClickEventArgs e)
        {
            //navigationFrame.SelectedPageIndex = 16;
            //officeNavigationBar.SelectedItem = null;
        }

        private void ConsReadButton_Click(object sender, EventArgs e)
        {

            Thread thread = new Thread(c => {
                MethodInvoker methodInvoker = new MethodInvoker(ShowFormConsRead);
                BeginInvoke(methodInvoker);
            });
            thread.Start();

        }

        private void ShowFormConsRead()
        {
            Xchip_ConsReadWin xchip_ConsReadWin = Xchip_ConsReadWin.GetInstance(IsUsbOpen);
            Xchip_ConsReadWin ot = Xchip_ConsReadWin.GetInstance();
            ot.StartPosition = FormStartPosition.CenterScreen;
            ot.sPortTemp = sPortTemp;
            //ot.ShowDialog();
            ot.Show();
            ot.Focus();

        }


        private void barButtonItem24_ItemClick(object sender, DevExpress.XtraBars.ItemClickEventArgs e)
        {
            //SetOpenSport();
            //navigationFrame.SelectedPageIndex = 18;
            //officeNavigationBar.SelectedItem = null;
        }

        private void barButtonItem15_ItemClick(object sender, DevExpress.XtraBars.ItemClickEventArgs e)
        {
            //if (navigationFrame.Pages.Any(c => c.Caption == "page_ToBin_Security"))
            //{
            //    navigationFrame.SelectedPageIndex = navigationFrame.Pages.FindIndex(c => c.Caption == "page_ToBin_Security");

            //}
            //else
            //{

            //    this.splashScreenManager1.ShowWaitForm();
            //    NavigationPage page = new NavigationPage();

            //    xChip_ToBin_Security = new XChip_ToBin_Security(Bincurrency_BLL, Serialdata_BLL , true);
            //    xChip_ToBin_Security.Dock = DockStyle.Fill;
            //    page.Controls.Add(xChip_ToBin_Security);
            //    page.Name = "page_ToBin_Security";
            //    navigationFrame.Pages.Add(page);
            //    navigationFrame.SelectedPage = page;
            //    this.splashScreenManager1.CloseWaitForm();
            //}

            this.splashScreenManager1.ShowWaitForm();
            NavigationPage page = new NavigationPage();
            if (null != xChip_ToBin_Security)
            {
                xChip_ToBin_Security.isSecurity = true;
            }
            xChip_ToBin_Security = XChip_ToBin_Security.Instance(Bincurrency_BLL, Serialdata_BLL, sPortTemp, true);
            xChip_ToBin_Security.Dock = DockStyle.Fill;
            page.Controls.Add(xChip_ToBin_Security);
            page.Name = "page_ToBin_Security";
            navigationFrame.Pages.Add(page);
            navigationFrame.SelectedPage = page;
            this.splashScreenManager1.CloseWaitForm();
            //SetOpenSport();
            //xChip_ToBin_Security1.Bincurrency_BLL = new bincurrencyManager();
            //xChip_ToBin_Security1.Serialdata_BLL = new serialdataManager();
            //navigationFrame.SelectedPage = Page_SecurityBin;

            //officeNavigationBar.SelectedItem = null;
        }

        private void btn_CRL_ItemClick(object sender, DevExpress.XtraBars.ItemClickEventArgs e)
        {
            if (navigationFrame.Pages.Any(c => c.Caption == "page_CRL"))
            {
                //navigationFrame.SelectedPageIndex = navigationFrame.Pages.FindIndex(c => c.Caption == "page_CRL");
                navigationFrame.SelectedPage = (INavigationPage)navigationFrame.Pages.FindFirst(c => c.Caption == "page_CRL");
                xChip_CRL.sPortTemp = sPortTemp;
            }
            else
            {
                WaitBefore.Start("请耐心等待...", "正在努力工作中");
                NavigationPage page = new NavigationPage();
                xChip_CRL = new XChip_CRL(sPortTemp, addressregisterBll);
                xChip_CRL.Dock = DockStyle.Fill;
                xChip_CRL.sPortTemp = sPortTemp;
                page.Controls.Add(xChip_CRL);
                page.Name = "page_CRL";
                navigationFrame.Pages.Add(page);
                navigationFrame.SelectedPage = page;
                WaitBefore.Close();
            }
            //SetOpenSport();
            //navigationFrame.SelectedPage = page_CRL;
            //officeNavigationBar.SelectedItem = null;
        }

        private void btn_CADJ_ItemClick(object sender, DevExpress.XtraBars.ItemClickEventArgs e)
        {
            if (navigationFrame.Pages.Any(c => c.Caption == "page_CADJ"))
            {
                //navigationFrame.SelectedPageIndex = navigationFrame.Pages.FindIndex(c => c.Caption == "page_CADJ");
                navigationFrame.SelectedPage = (INavigationPage)navigationFrame.Pages.FindFirst(c => c.Caption == "page_CADJ");
                xChip_CADJ.sPortTemp = sPortTemp;
            }
            else
            {
                WaitBefore.Start("请耐心等待...", "正在努力工作中");
                NavigationPage page = new NavigationPage();
                xChip_CADJ = new XChip_CADJ_C(sPortTemp, addressregisterBll);
                xChip_CADJ.Dock = DockStyle.Fill;
                xChip_CADJ.sPortTemp = sPortTemp;
                page.Controls.Add(xChip_CADJ);
                page.Name = "page_CADJ";
                navigationFrame.Pages.Add(page);
                navigationFrame.SelectedPage = page;
                WaitBefore.Close();
            }
            //SetOpenSport();
            //navigationFrame.SelectedPage = page_CADJ;
            //officeNavigationBar.SelectedItem = null;
        }


        private void Sensor_i2cReadWrite_Click(object sender, EventArgs e)
        {
            SerialSend.WriteRegister(0x20000069, 0x00, sPortTemp);

            XChip_SensorI2cForm xchip_sensorI2cForm = XChip_SensorI2cForm.GetInstance(IsUsbOpen);
            xchip_sensorI2cForm.StartPosition = FormStartPosition.CenterScreen;
            xchip_sensorI2cForm.ClearEvent();
            xchip_sensorI2cForm.SendSensor_i2cClick += setShowMsg;
            xchip_sensorI2cForm.SPortTemp = sPortTemp;
            xchip_sensorI2cForm.Show();
            xchip_sensorI2cForm.Focus();
        }

        private void btnShowPwd_Click(object sender, EventArgs e)
        {
            if (comBoxBaudRate.Properties.PasswordChar == '*')
            {
                comBoxBaudRate.Properties.DisplayMember = comBoxBaudRate.Properties.ValueMember;
                comBoxBaudRate.Properties.PasswordChar = '\0';
                btnShowPwd.ImageOptions.ImageIndex = 0;
            }
            else
            {
                comBoxBaudRate.Properties.DisplayMember = "DisplayMember";
                comBoxBaudRate.Properties.PasswordChar = '*';
                btnShowPwd.ImageOptions.ImageIndex = 1;
            }
        }

        private void btn_FileCheck_ItemClick(object sender, DevExpress.XtraBars.ItemClickEventArgs e)
        {
            OpenFileDialog openFileDialog1 = new OpenFileDialog();
            openFileDialog1.Filter = "TXT Files(*.txt)|*.txt|All Files(*.*)|*.*";
            if (openFileDialog1.ShowDialog() == DialogResult.OK)
            {
                var msg = FileHelper.CheckFiles(openFileDialog1.FileName);
                if (!string.IsNullOrEmpty(msg))
                {
                    if (msg.Length > 1000)
                    {
                        DevExpress.XtraEditors.XtraMessageBox.Show($"问题数据过多！已无法显示！请检查文件！");
                    }
                    else
                    {
                        DevExpress.XtraEditors.XtraMessageBox.Show(msg);
                    }
                }
                else
                {
                    DevExpress.XtraEditors.XtraMessageBox.Show("校验已完成！未检测出问题！");
                }
            }
        }

        private void btn_TVE_Reset_Click(object sender, EventArgs e)
        {
            if (!sPortTemp.IsOpen && !IsUsbOpen && !m_open)
            {
                DevExpress.XtraEditors.XtraMessageBox.Show("可用端口未打开");
                return;
            }
            //SerialSend.WriteRegister(0x80500039, 0x03, sPortTemp);
            //SerialSend.WriteRegister(0x8050001a, 0x01, sPortTemp);
            //SerialSend.WriteRegister(0x80500019, 0x80, sPortTemp);

            //SerialSend.WriteRegister(0x80500039, 0x00, sPortTemp);
            //SerialSend.WriteRegister(0x8050001a, 0x00, sPortTemp);
            //SerialSend.WriteRegister(0x80500019, 0x00, sPortTemp);
            SerialSend.WriteRegister(0x80500137, 0xab, sPortTemp);
        }

        private void check_IspOSD_CheckedChanged(object sender, EventArgs e)
        {
            if (!sPortTemp.IsOpen && !IsUsbOpen && !m_open)
            {
                DevExpress.XtraEditors.XtraMessageBox.Show("可用端口未打开");
                return;
            }
            if (evenMask)
                return;
            uint temp = (uint)SerialSend.ReadRegister(0x80300004, sPortTemp);
            if (check_IspOSD.Checked)
            {
                SerialSend.WriteRegister(0x80300004, temp | 0x80, sPortTemp);
            }
            else
            {
                SerialSend.WriteRegister(0x80300004, temp & 0x7f, sPortTemp);
            }
        }

        private void btn_RefreshAeState_Click(object sender, EventArgs e)
        {
            //if (!sPortTemp.IsOpen && !IsUsbOpen && !m_open)
            //{
            //    DevExpress.XtraEditors.XtraMessageBox.Show("可用端口未打开");
            //    return;
            //}
            //switch (SerialSend.ReadRegister((Convert.ToUInt32(XChipHelp.XChipAe.Where(c => c.NameType.ToLower() == "Scene_Mode".ToLower()).First().Address, 16)), sPortTemp) & 0x3)
            //{
            //    case 0:
            //        txt_CurScene.Text = "Day";
            //        break;
            //    case 1:
            //        txt_CurScene.Text = "Night";
            //        break;
            //    case 2:
            //        txt_CurScene.Text = "Midnight";
            //        break;
            //    default:
            //        break;
            //}
            //long nHighest, nHigh, nMid, nLow, nValue;
            //nHigh = SerialSend.ReadRegister((Convert.ToUInt32(XChipHelp.XChipAe.Where(c => c.NameType.ToLower() == "AE_AVRBIRGHT_h".ToLower()).First().Address, 16)), sPortTemp);
            //nLow = SerialSend.ReadRegister((Convert.ToUInt32(XChipHelp.XChipAe.Where(c => c.NameType.ToLower() == "AE_AVRBIRGHT_L".ToLower()).First().Address, 16)), sPortTemp);

            //nValue = (nHigh << 8) | nLow;
            //AE_AVRBIRGHT.Text = SerialSend.ReadRegister(0x80300053, sPortTemp).ToString("X2");

            //nHighest = SerialSend.ReadRegister((Convert.ToUInt32(XChipHelp.XChipAe.Where(c => c.NameType.ToLower() == "AE_EDIT_EXPLINE_h".ToLower()).First().Address, 16)), sPortTemp);
            //nHigh = SerialSend.ReadRegister((Convert.ToUInt32(XChipHelp.XChipAe.Where(c => c.NameType.ToLower() == "AE_EDIT_EXPLINE_m0".ToLower()).First().Address, 16)), sPortTemp);
            //nMid = SerialSend.ReadRegister((Convert.ToUInt32(XChipHelp.XChipAe.Where(c => c.NameType.ToLower() == "AE_EDIT_EXPLINE_m1".ToLower()).First().Address, 16)), sPortTemp);
            //nLow = SerialSend.ReadRegister((Convert.ToUInt32(XChipHelp.XChipAe.Where(c => c.NameType.ToLower() == "AE_EDIT_EXPLINE_l".ToLower()).First().Address, 16)), sPortTemp);

            //nValue = (nHighest << 20) | (nHigh << 12) | (nMid << 4) | (nLow >> 4);
            //AE_EDIT_EXPLINE.Text = nValue.ToString("X2");


            //nHighest = SerialSend.ReadRegister((Convert.ToUInt32(XChipHelp.XChipAe.Where(c => c.NameType.ToLower() == "AE_SENSORGAIN_h".ToLower()).First().Address, 16)), sPortTemp);
            //nHigh = SerialSend.ReadRegister((Convert.ToUInt32(XChipHelp.XChipAe.Where(c => c.NameType.ToLower() == "AE_SENSORGAIN_m0".ToLower()).First().Address, 16)), sPortTemp);
            //nMid = SerialSend.ReadRegister((Convert.ToUInt32(XChipHelp.XChipAe.Where(c => c.NameType.ToLower() == "AE_SENSORGAIN_m1".ToLower()).First().Address, 16)), sPortTemp);
            //nLow = SerialSend.ReadRegister((Convert.ToUInt32(XChipHelp.XChipAe.Where(c => c.NameType.ToLower() == "AE_SENSORGAIN_l".ToLower()).First().Address, 16)), sPortTemp);

            //nValue = (nHighest << 24) | (nHigh << 16) | (nMid << 8) | nLow;
            //AE_SENSORGAIN.Text = ((float)nValue / 0x20).ToString("0.00");

            ////if (AE_ISP_GAINENABLE_EN.CheckState == CheckState.Checked)
            //if (((SerialSend.ReadRegister((Convert.ToUInt32(XChipHelp.XChipAe.Where(c => c.NameType.ToLower() == "Isp_Gain_en".ToLower()).First().Address, 16)), sPortTemp)) >> 5 & 0x01) == 1)
            //{
            //    nHigh = SerialSend.ReadRegister((Convert.ToUInt32(XChipHelp.XChipAe.Where(c => c.NameType.ToLower() == "AE_EDIT_ISPGAIN_h".ToLower()).First().Address, 16)), sPortTemp);
            //    nLow = SerialSend.ReadRegister((Convert.ToUInt32(XChipHelp.XChipAe.Where(c => c.NameType.ToLower() == "AE_EDIT_ISPGAIN_l".ToLower()).First().Address, 16)), sPortTemp);

            //    nValue = (nHigh << 8) | nLow;
            //    AE_EDIT_ISPGAIN.Text = ((float)nValue / 0x4).ToString("0.00");
            //}
            //else
            //{
            //    AE_EDIT_ISPGAIN.Text = "1.0";
            //}

            //nHighest = SerialSend.ReadRegister((Convert.ToUInt32(XChipHelp.XChipAe.Where(c => c.NameType.ToLower() == "AE_EDIT_GAIN_h".ToLower()).First().Address, 16)), sPortTemp);
            //nHigh = SerialSend.ReadRegister((Convert.ToUInt32(XChipHelp.XChipAe.Where(c => c.NameType.ToLower() == "AE_EDIT_GAIN_m0".ToLower()).First().Address, 16)), sPortTemp);
            //nMid = SerialSend.ReadRegister((Convert.ToUInt32(XChipHelp.XChipAe.Where(c => c.NameType.ToLower() == "AE_EDIT_GAIN_m1".ToLower()).First().Address, 16)), sPortTemp);
            //nLow = SerialSend.ReadRegister((Convert.ToUInt32(XChipHelp.XChipAe.Where(c => c.NameType.ToLower() == "AE_EDIT_GAIN_l".ToLower()).First().Address, 16)), sPortTemp);

            //nValue = (nHighest << 24) | (nHigh << 16) | (nMid << 8) | nLow;
            //AE_EDIT_GAIN.Text = ((float)nValue / 0x20).ToString("0.00");
        }
        /// <summary>
        /// bin密钥设置
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void barButtonItem1_ItemClick_1(object sender, DevExpress.XtraBars.ItemClickEventArgs e)
        {
            XChip_BinPassWord binF = new XChip_BinPassWord();
            binF.StartPosition = FormStartPosition.CenterScreen;
            binF.ShowDialog();
        }

        private void barButtonItem3_ItemClick_1(object sender, DevExpress.XtraBars.ItemClickEventArgs e)
        {
            if (navigationFrame.Pages.Any(c => c.Caption == "page_ToolBox"))
            {
                //navigationFrame.SelectedPageIndex = navigationFrame.Pages.FindIndex(c => c.Caption == "page_ToolBox");
                navigationFrame.SelectedPage = (INavigationPage)navigationFrame.Pages.FindFirst(c => c.Caption == "page_ToolBox");

            }
            else
            {
                this.splashScreenManager1.ShowWaitForm();
                NavigationPage page = new NavigationPage();
                xChip_ToolBox = new XChip_ToolBox();
                xChip_ToolBox.Dock = DockStyle.Fill;
                page.Controls.Add(xChip_ToolBox);
                page.Name = "page_ToolBox";
                navigationFrame.Pages.Add(page);
                navigationFrame.SelectedPage = page;
                this.splashScreenManager1.CloseWaitForm();
            }
            //navigationFrame.SelectedPage = page_ToolBox;
            //officeNavigationBar.SelectedItem = null;
        }

        private void simpleButton6_Click(object sender, EventArgs e)
        {
            if (!sPortTemp.IsOpen)
            {
                DevExpress.XtraEditors.XtraMessageBox.Show("可用端口未打开");
                return;
            }
            FlashBase fb = new FlashBase(sPortTemp);
            fb.SendEvent += setShowMsg;
            fb.SendRegDataARM(0x21, 0x80500137, 0x57000000, sPortTemp);
        }

        private void simpleButton7_Click(object sender, EventArgs e)
        {
            if (!sPortTemp.IsOpen)
            {
                DevExpress.XtraEditors.XtraMessageBox.Show("可用端口未打开");
                return;
            }
            FlashBase fb = new FlashBase(sPortTemp);
            fb.SendEvent += setShowMsg;
            fb.SendRegDataARM(0x21, 0x80500137, 0x58000000, sPortTemp);
        }

        private void simpleButton11_Click(object sender, EventArgs e)
        {
            if (!sPortTemp.IsOpen)
            {
                DevExpress.XtraEditors.XtraMessageBox.Show("可用端口未打开");
                return;
            }
            FlashBase fb = new FlashBase(sPortTemp);
            fb.SendEvent += setShowMsg;
            fb.SendRegDataARM(0x21, 0x80500137, 0x59000000, sPortTemp);
        }

        private void simpleButton9_Click(object sender, EventArgs e)
        {
            if (!sPortTemp.IsOpen)
            {
                DevExpress.XtraEditors.XtraMessageBox.Show("可用端口未打开");
                return;
            }
            FlashBase fb = new FlashBase(sPortTemp);
            fb.SendEvent += setShowMsg;
            fb.SendRegDataARM(0x21, 0x80500137, 0x55000000, sPortTemp);
        }

        private void simpleButton10_Click(object sender, EventArgs e)
        {
            if (!sPortTemp.IsOpen)
            {
                DevExpress.XtraEditors.XtraMessageBox.Show("可用端口未打开");
                return;
            }
            FlashBase fb = new FlashBase(sPortTemp);
            fb.SendEvent += setShowMsg;
            fb.SendRegDataARM(0x21, 0x80500137, 0x56000000, sPortTemp);
        }

        private void gpioBtn_ItemClick(object sender, DevExpress.XtraBars.ItemClickEventArgs e)
        {
            if (navigationFrame.Pages.Any(c => c.Caption == "page_GPIO"))
            {
                //navigationFrame.SelectedPageIndex = navigationFrame.Pages.FindIndex(c => c.Caption == "page_GPIO");
                navigationFrame.SelectedPage = (INavigationPage)navigationFrame.Pages.FindFirst(c => c.Caption == "page_GPIO");

                xChip_Gpio.sPortTemp = sPortTemp;
            }
            else
            {
                WaitBefore.Start("请耐心等待...", "正在努力工作中");
                NavigationPage page = new NavigationPage();
                xChip_Gpio = new XChip_Gpio(sPortTemp, addressregisterBll);
                xChip_Gpio.Dock = DockStyle.Fill;
                xChip_Gpio.sPortTemp = sPortTemp;
                page.Controls.Add(xChip_Gpio);
                page.Name = "page_GPIO";
                navigationFrame.Pages.Add(page);
                navigationFrame.SelectedPage = page;
                WaitBefore.Close();
            }
            //navigationFrame.SelectedPage = page_Gpio;
        }

        private void barStaticItem1_ItemClick(object sender, DevExpress.XtraBars.ItemClickEventArgs e)
        {
            XChip_VersionPassWord xvp = new XChip_VersionPassWord();
            xvp.StartPosition = FormStartPosition.CenterScreen;
            xvp.ShowDialog();
        }

        private void barButtonItem4_ItemClick_1(object sender, DevExpress.XtraBars.ItemClickEventArgs e)
        {
            if (navigationFrame.Pages.Any(c => c.Caption == "page_CADJ"))
            {
                //navigationFrame.SelectedPageIndex = navigationFrame.Pages.FindIndex(c => c.Caption == "page_CADJ");
                navigationFrame.SelectedPage = (INavigationPage)navigationFrame.Pages.FindFirst(c => c.Caption == "page_CADJ");

                xChip_CADJ.sPortTemp = sPortTemp;
            }
            else
            {
                this.splashScreenManager1.ShowWaitForm();
                NavigationPage page = new NavigationPage();
                xChip_CADJ = new XChip_CADJ_C(sPortTemp, addressregisterBll);
                xChip_CADJ.Dock = DockStyle.Fill;
                xChip_CADJ.sPortTemp = sPortTemp;
                page.Controls.Add(xChip_CADJ);
                page.Name = "page_CADJ";
                navigationFrame.Pages.Add(page);
                navigationFrame.SelectedPage = page;
                this.splashScreenManager1.CloseWaitForm();
            }
            //SetOpenSport();
            //navigationFrame.SelectedPage = Page_Cadj_C;
        }
        /// <summary>
        /// 更新IQ
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void updateIqBtn_Click(object sender, EventArgs e)
        {
           
            WaitBefore.Start("参数导出", "正在加载中", 60);
            //if (xChip_Driving_11.IsCheckDriving())
            //{
            //   var guid = xChip_Driving_11.GuidNo;
            //   var Bincurrency_BLL = new bincurrencyManager();
            //   var list =  Bincurrency_BLL.GetListToDefault(guid);
            //    foreach (var item in list)
            //    {
            //        if (item.BinId == 112)
            //        {
            //            var tempName = Path.GetFileNameWithoutExtension(item.BinInPath) ;
            //            var end = tempName.IndexOf("_iq");
            //            if (end != -1)
            //            {
            //                tempName = tempName.Substring(0, end) + "_iq_" + DateTime.Now.ToString("MMddHHmmss");
            //            }
            //            else {
            //                tempName = tempName + "_iq_" + DateTime.Now.ToString("MMddHHmmss");
            //            }

            //            var tempPath = System.IO.Path.GetDirectoryName(item.BinInPath) ;
            //            if (System.IO.Path.GetDirectoryName(item.BinInPath).Contains("SettingTemp"))
            //            {
            //                tempPath = System.IO.Path.GetDirectoryName(item.BinInPath) + "\\";
            //            }
            //            else
            //            {
            //                tempPath = System.IO.Path.GetDirectoryName(item.BinInPath) + "\\SettingTemp\\";
            //            }
            //            if (!Directory.Exists(tempPath))Directory.CreateDirectory(tempPath);
            //            var pSaveFilePath = $"{tempPath}{tempName}{Path.GetExtension(item.BinInPath)}";
            //            if (!File.Exists(pSaveFilePath))//必须判断要复制的文件是否存在
            //            {
            //                File.Copy(item.BinInPath, pSaveFilePath, true);//三个参数分别是源文件路径，存储路径，若存储路径有相同文件是否替换
            //            }
            //            //更新IQ
            //            var msg = UpdateParameterNewIQ(pSaveFilePath);
            //            if (msg.state == MsgSt.Success)
            //            {
            //                if (File.Exists(pSaveFilePath))
            //                {
            //                    File.Delete(pSaveFilePath);
            //                }
            //                File.WriteAllLines(pSaveFilePath, msg.data, Encoding.Default);
            //                var model =   SettingList_Help.SetTips16.Where(c => c.data != null && c.data.Last().DisplayMember == item.BinInName).ToList();
            //                foreach (var stitem in SettingList_Help.SetTips16)
            //                {
            //                    if (stitem.data != null&& stitem.comData != null)
            //                    {
            //                        //var modelBC = Bincurrency_BLL.GetSingle(c => c.GuidId == guid && c.BinId == 112 && c.BinInName == stitem.data.Last().DisplayMember );
            //                        List<string> AList =msg.data;
            //                        List<string> BList = File.ReadAllLines(stitem.comData.Last().ValueMember, Encoding.Default).ToList();
            //                        string pSavePath = string.Format("{0}\\Lib\\xc{1}_setting\\", Application.StartupPath, ConfigurationManager.AppSettings["xcVersion"]);
            //                        string pLocalName = System.IO.Path.GetFileName(item.BinInPath); //获取文件名
            //                        string path = pSavePath + $"\\IQCom_{ Path.GetFileNameWithoutExtension(pLocalName)}_{item.SerialNo}_{AppHelper.GetTimeStamp()}.txt";
            //                        FileHelper.ComMergeFiles(AList, BList, path, "xchip_i2c_bypass_on_regs", "#region config");
            //                        var commonPath = OpenSettingToFile(path, xChip_Driving_11._isPollingSetOk,xChip_Driving_11.IsOsd,xChip_Driving_11._isOsdVerCheck);
            //                        item.BinOutPath = commonPath;
            //                        item.BinOutName = Path.GetFileName(commonPath);
            //                        item.LengthAddress = HeaderHelper.FilePathLengthComplement(commonPath);
            //                        Bincurrency_BLL.Update(item);
            //                    }
            //                }
            //            }
            //            else {
            //                XtraMessageBox.Show($"更新错误：{msg.msg}", "提示", MessageBoxButtons.OK, MessageBoxIcon.Error);
            //            }
            //        }
            //    }
            //}
            //if (xChip_Security641.IsCheckSecurity())
            //{
            //    var guid = xChip_Security641.GuidNo;
            //    var Bincurrency_BLL = new bincurrencyManager();
            //    var list = Bincurrency_BLL.GetList(c => c.GuidId == guid);
            //    foreach (var item in list)
            //    {
            //        if (item.BinId == 112 && item.BinOutName.Contains("_iq_"))
            //        {
            //            if (string.IsNullOrEmpty(item.BinInPath))
            //            {
            //                continue;
            //            }
            //            var tempName = Path.GetFileNameWithoutExtension(item.BinInPath);
            //            var end = tempName.IndexOf("_iq");
            //            tempName = tempName.Substring(0, end) + "_iq_" + DateTime.Now.ToString("MMddHHmmss");
            //            var tempPath = System.IO.Path.GetDirectoryName(item.BinInPath);
            //            if (System.IO.Path.GetDirectoryName(item.BinInPath).Contains("SettingTemp"))
            //            {
            //                tempPath = System.IO.Path.GetDirectoryName(item.BinInPath) + "\\";
            //            }
            //            else
            //            {
            //                tempPath = System.IO.Path.GetDirectoryName(item.BinInPath) + "\\SettingTemp\\";
            //            }
            //            if (!Directory.Exists(tempPath)) Directory.CreateDirectory(tempPath);
            //            var pSaveFilePath = $"{tempPath}{tempName}{Path.GetExtension(item.BinInPath)}";
            //            if (!File.Exists(pSaveFilePath))//必须判断要复制的文件是否存在
            //            {
            //                File.Copy(item.BinInPath, pSaveFilePath, true);//三个参数分别是源文件路径，存储路径，若存储路径有相同文件是否替换
            //            }
            //            //更新IQ
            //            var msg = UpdateParameterNewIQ(pSaveFilePath);
            //            if (msg.state == MsgSt.Success)
            //            {
            //                string pSavePath = string.Format("{0}\\Lib\\xc{1}_setting\\", Application.StartupPath, ConfigurationManager.AppSettings["xcVersion"]);
            //                string pLocalName = System.IO.Path.GetFileName(item.BinInPath); //获取文件名
            //                string path = pSavePath + $"\\IQCom_{ Path.GetFileNameWithoutExtension(pLocalName)}_{AppHelper.GetTimeStamp()}.txt";
            //                var mcount = list.Find(c => c.BinId == 117);
            //                File.WriteAllLines(pSaveFilePath, msg.data, Encoding.Default);
            //                if (!string.IsNullOrEmpty(mcount.BinInPath))
            //                {
            //                    List<string> AList = msg.data;
            //                    List<string> BList = File.ReadAllLines(mcount.BinInPath, Encoding.Default).ToList();
            //                    int aStartIndex = AList.FindIndex(c => c.Contains("xchip_i2c_bypass_on_regs"));
            //                    var ispath = FileHelper.ComMergeFiles(AList, BList, path, "xchip_i2c_bypass_on_regs", "#region config");

            //                }
            //                else
            //                {
            //                    path = item.BinInPath;
            //                }
            //                var commonPath = OpenSettingToFile64(path, xChip_Security641.isPollingSetOk, xChip_Security641.isPress_key, xChip_Security641.isOsdVerCheck);
            //                item.BinOutPath = commonPath;
            //                item.BinOutName = Path.GetFileName(commonPath);
            //                item.LengthAddress = HeaderHelper.FilePathLengthComplement(commonPath);
            //                item.FileStatus = 2;
            //                Bincurrency_BLL.Update(item);
            //            }
            //            else
            //            {
            //                XtraMessageBox.Show($"更新错误：{msg.msg}", "提示", MessageBoxButtons.OK, MessageBoxIcon.Error);
            //            }

            //        }
            //    }
            //}
            WaitBefore.Close();
        }


        /// <summary>
        /// 更新IQ
        /// </summary>
        /// <param name="filepath"></param>
        /// <returns></returns>

        private XChip_Common.MsgString<List<string>> UpdateParameterNewIQ(string filepath)
        {
            XChip_Common.MsgString<List<string>> msg = new MsgString<List<string>>();
            if (!sPortTemp.IsOpen)
            {
                msg.state = MsgSt.Warn;
                msg.msg = $"可用端口未打开！";
                return msg;
            }
            StreamReader sr = new StreamReader(filepath, Encoding.Default);
            List<string> listStr = new List<string>();
            string line;
            while ((line = sr.ReadLine()) != null)
            {
                listStr.Add(line);
            }
            sr.Close();

            //WaitBefore.Start("参数导出", "正在加载中", 60);
            var Pe_patch_dal = new parameter_export_patchManager();
            var patchList = Pe_patch_dal.GetList();

            //全局变量 0xfffd  0xfffe
            string add = "80";//  0xfffd
            string addval = string.Empty; //0xfffe
            string duVal = string.Empty; //读取的值
            //IQ_common
            var commonStart = Array.FindIndex(listStr.ToArray(), t => t.IndexOf("IQ_common", StringComparison.InvariantCultureIgnoreCase) >= 0);
            #region 判断IQ_common的起始索引
            if (commonStart < 0)
            {
                commonStart = Array.FindIndex(listStr.ToArray(), t => t.IndexOf("AE sensor", StringComparison.InvariantCultureIgnoreCase) >= 0);
                if (commonStart < 0)
                {
                    commonStart = Array.FindIndex(listStr.ToArray(), t => t.IndexOf("Step 10", StringComparison.InvariantCultureIgnoreCase) >= 0);
                }
            }
            #endregion
            //IQ_oneself
            var commonEnd = Array.FindIndex(listStr.ToArray(), t => t.IndexOf("IQ_oneself", StringComparison.InvariantCultureIgnoreCase) >= 0);
            #region 判断setp2的起始索引
            if (commonEnd < 0)
            {
                commonEnd = Array.FindIndex(listStr.ToArray(), t => t.IndexOf("avg_size", StringComparison.InvariantCultureIgnoreCase) >= 0);

            }
            #endregion
            if (commonStart == -1 || commonEnd == -1)
            {
                msg.state = MsgSt.Lose;
                msg.msg = $"无法找到指定更新位置，请先设置";
                return msg;
            }
            //WaitBefore.Start("参数导出", "正在加载中", 60);
            SerialSend.isDebug = false;
            for (int i = commonStart; i < commonEnd; i++)
            {
                string[] col = listStr[i].Replace('，', ',').Split(',');
                if (col.Count() > 2)
                {
                    string colFirst = col.First().Trim().ToLower();
                    //if (colFirst.Contains("0x3c42"))
                    //{

                    //}
                    //过滤关键字
                    if (colFirst == "0xffff" || colFirst == "0xfff3" || colFirst == "0xfff6" || colFirst == "0xfff7" || colFirst == "0xfff8" || colFirst == "0xfff9" || colFirst == "0xfffa" || colFirst == "0xfff0" || colFirst == "0xfff1")
                    {
                        continue;
                    }
                    else if (colFirst == "0xfffd")
                    {
                        add = col[1].Replace("0x", "");
                    }
                    else if (colFirst == "0xfffe")
                    {
                        addval = col[1].Replace("0x", "");
                    }
                    else if (colFirst.Contains("0x") && !colFirst.Contains("//"))
                    {
                        try
                        {
                            string sonVal = colFirst.Replace("0x", "").Replace(" ", "");
                            duVal = (add + addval + sonVal.PadLeft(4, '0')).Replace("0x", "").Replace(" ", "").ToLower();
                            if (duVal.Length != 8 || duVal == "80300000" || duVal == "80300001" || duVal == "80300002" || duVal == "80300003" || duVal == "80300004"
                                     || duVal == "8014062c")
                                continue;

                            long tempVal = -1;

                            if (patchList.Count != 0 && patchList.Select(c => c.ReadAddr).Contains(duVal))
                            {
                                var patchModel = patchList.First(c => c.ReadAddr.Contains(duVal));
                                if (string.IsNullOrEmpty(patchModel.ConditionAddr) && string.IsNullOrEmpty(patchModel.RelationAddr) && !string.IsNullOrEmpty(patchModel.Val))
                                {
                                    tempVal = Convert.ToUInt32(patchModel.Val, 16);
                                }
                                else if (!string.IsNullOrEmpty(patchModel.ConditionAddr) && SerialSend.ReadRegister(Convert.ToUInt32(patchModel.ConditionAddr, 16), sPortTemp) == 0)
                                {
                                    tempVal = SerialSend.ReadRegister(Convert.ToUInt32(patchModel.ReadAddr, 16), sPortTemp);
                                }
                                else if (string.IsNullOrEmpty(patchModel.RelationAddr) && string.IsNullOrEmpty(patchModel.ConditionAddr) && !string.IsNullOrEmpty(patchModel.Bit))
                                {
                                    tempVal = Convert.ToUInt32(patchModel.Bit, 16);
                                }
                                else
                                {
                                    if (!string.IsNullOrEmpty(patchModel.Bit) && patchModel.Bit.Contains("&0x7f"))
                                    {
                                        tempVal = SerialSend.ReadRegister(Convert.ToUInt32(patchModel.RelationAddr, 16), sPortTemp) & 0x7f;
                                    }
                                    else
                                    {
                                        tempVal = SerialSend.ReadRegister(Convert.ToUInt32(patchModel.RelationAddr, 16), sPortTemp);
                                    }

                                }
                            }
                            else
                            {
                                tempVal = SerialSend.ReadRegister(Convert.ToUInt32(duVal, 16), sPortTemp);
                                switch (duVal)
                                {
                                    case "80500021":
                                        tempVal |= 0x08;
                                        break;
                                    case "8050001c":
                                        tempVal |= 0x01;
                                        break;
                                    case "80200002":
                                        tempVal &= 0x7f;
                                        break;
                                    case "8020002c":
                                        tempVal |= 0x01;
                                        break;
                                    case "80500200":
                                        tempVal &= 0x0f;
                                        break;
                                    default:
                                        break;
                                }
                                //col[1] = col[1].Contains(" ") ? " 0x" + tempVal.ToString("x2") : "0x" + tempVal.ToString("x2");

                            }
                            string oldVal = col[1].Replace("0x", "").Replace(" ", "");
                            col[1] = col[1].Replace(oldVal, tempVal.ToString("x2"));
                            listStr[i] = string.Join(",", col);
                        }
                        catch (Exception ex)
                        {
                            WaitBefore.Close();
                            DevExpress.XtraEditors.XtraMessageBox.Show(ex.ToString());
                            throw;
                        }
                    }
                }
            }
            SerialSend.isDebug = true;
            //WaitBefore.Close();
            msg.state = MsgSt.Success;
            msg.data = listStr;
            return msg;
        }
        /// <summary>
        ///  更新安防文件文件
        /// </summary>
        /// <param name="openFile">文件路径</param>
        /// <returns></returns>
        public string OpenSettingToFile64(string openFile, bool _isPollingSetOk, int _isPress_key, bool _isOsdVerCheck)
        {
            string pSavePath = string.Format("{0}\\Lib\\xc{1}_setting\\", Application.StartupPath, ConfigurationManager.AppSettings["xcVersion"]);
            string pLocalName = System.IO.Path.GetFileName(openFile); //获取文件名
            string path = pSavePath + "\\Flash_" + Path.GetFileNameWithoutExtension(pLocalName) + ".txt";
            var rList = Setting2Help.ReadTextFileToList(openFile);
            if (_isPollingSetOk)
            {
                if (_isPress_key == 0)
                {
                    rList.AddRange(ParaHelp.CreateBinPressKey());
                    uint pin = Convert.ToUInt16(ParaHelp.Bin_Press_Key.Find(p => p.PKey == "0x0b38").PValue, 16);
                    List<string[]> tempList = new List<string[]>();
                    #region 解析rlist存入tempList
                    string addrPageH = "80";
                    string addrPageM = string.Empty;
                    foreach (string line in rList)
                    {
                        string[] temp = new string[3];
                        temp[0] = line;
                        string[] col = line.ToLower().Replace('，', ',').Split(',');
                        string colFirst = col.First().Trim();
                        if (col.Count() > 2)
                        {
                            if (colFirst == "0xfffd")
                            {
                                addrPageH = col[1].Replace("0x", "").Trim();
                            }
                            else if (colFirst == "0xfffe")
                            {
                                addrPageM = col[1].Replace("0x", "").Trim();
                            }
                            else if (colFirst.Contains("0x") && !colFirst.Contains("//"))
                            {
                                temp[1] = addrPageH + addrPageM + colFirst.Replace("0x", "").Replace(" ", "");
                                temp[2] = col[1].Replace("0x", "").Replace(" ", "");
                            }
                        }
                        tempList.Add(temp);
                    }
                    #endregion
                    #region 更新寄存器方法
                    Action<string, string> tempUpReg = new Action<string, string>(
                                 (string addr, string value) =>
                                 {
                                     string tempstr = tempList.LastOrDefault(c => c[1] == addr).First();
                                     string[] tempStrArray = tempstr.Replace("，", ",").Split(',');
                                     tempStrArray[1] = value;
                                     tempList.Last(c => c[1] == addr)[0] = string.Join(",", tempStrArray);
                                 });
                    #endregion
                    string gpio8_15_en = tempList.LastOrDefault(c => c[1] == "80500201")?.GetValue(2).ToString();
                    string gpio8_15_dir = tempList.LastOrDefault(c => c[1] == "80500205")?.GetValue(2).ToString();
                    string gpio8_15_in_en = tempList.LastOrDefault(c => c[1] == "805000d1")?.GetValue(2).ToString();
                    switch (pin)
                    {
                        #region 更新按键轮询所选gpio相关寄存器
                        case 0://Gpio 2
                            string gpio0_7_en = tempList.LastOrDefault(c => c[1] == "80500200")?.GetValue(2).ToString();
                            string gpio0_7_dir = tempList.LastOrDefault(c => c[1] == "80500204")?.GetValue(2).ToString();
                            string gpio0_7_in_en = tempList.LastOrDefault(c => c[1] == "805000d0")?.GetValue(2).ToString();
                            if (string.IsNullOrEmpty(gpio0_7_en) || string.IsNullOrEmpty(gpio0_7_dir) || string.IsNullOrEmpty(gpio0_7_in_en))
                            {
                                tempList.Add(new string[3] { "0xfffd,0x80,\r\n0xfffe,0x50,", null, null });
                            }
                            if (string.IsNullOrEmpty(gpio0_7_en))
                            {
                                tempList.Add(new string[3] { "0x0200,0x04,", null, null });
                            }
                            else
                            {
                                uint tempVal = Convert.ToUInt16(gpio0_7_en, 16);
                                tempUpReg("80500200", "0x" + (tempVal | 0x04).ToString("x2"));
                            }
                            if (string.IsNullOrEmpty(gpio0_7_dir))
                            {
                                tempList.Add(new string[3] { "0x0204,0x00,", null, null });
                            }
                            else
                            {
                                uint tempVal = Convert.ToUInt16(gpio0_7_dir, 16);
                                tempUpReg("80500204", "0x" + (tempVal & 0xfb).ToString("x2"));
                            }
                            if (string.IsNullOrEmpty(gpio0_7_in_en))
                            {
                                tempList.Add(new string[3] { "0x00d0,0x04,", null, null });
                            }
                            else
                            {
                                uint tempVal = Convert.ToUInt16(gpio0_7_in_en, 16);
                                tempUpReg("805000d0", "0x" + (tempVal | 0x04).ToString("x2"));
                            }
                            break;
                        case 1://Gpio 8                           
                            if (string.IsNullOrEmpty(gpio8_15_en) || string.IsNullOrEmpty(gpio8_15_dir) || string.IsNullOrEmpty(gpio8_15_in_en))
                            {
                                tempList.Add(new string[3] { "0xfffd,0x80,\r\n0xfffe,0x50,", null, null });
                            }
                            if (string.IsNullOrEmpty(gpio8_15_en))
                            {
                                tempList.Add(new string[3] { "0x0201,0x01,", null, null });
                            }
                            else
                            {
                                uint tempVal = Convert.ToUInt16(gpio8_15_en, 16);
                                tempUpReg("80500201", "0x" + (tempVal | 0x01).ToString("x2"));
                            }
                            if (string.IsNullOrEmpty(gpio8_15_dir))
                            {
                                tempList.Add(new string[3] { "0x0205,0x00,", null, null });
                            }
                            else
                            {
                                uint tempVal = Convert.ToUInt16(gpio8_15_dir, 16);
                                tempUpReg("80500205", "0x" + (tempVal & 0xfe).ToString("x2"));
                            }
                            if (string.IsNullOrEmpty(gpio8_15_in_en))
                            {
                                tempList.Add(new string[3] { "0x00d1,0x01,", null, null });
                            }
                            else
                            {
                                uint tempVal = Convert.ToUInt16(gpio8_15_in_en, 16);
                                tempUpReg("805000d1", "0x" + (tempVal | 0x01).ToString("x2"));
                            }
                            break;
                        case 2://Gpio 9
                            if (string.IsNullOrEmpty(gpio8_15_en) || string.IsNullOrEmpty(gpio8_15_dir) || string.IsNullOrEmpty(gpio8_15_in_en))
                            {
                                tempList.Add(new string[3] { "0xfffd,0x80,\r\n0xfffe,0x50,", null, null });
                            }
                            if (string.IsNullOrEmpty(gpio8_15_en))
                            {
                                tempList.Add(new string[3] { "0x0201,0x02,", null, null });
                            }
                            else
                            {
                                uint tempVal = Convert.ToUInt16(gpio8_15_en, 16);
                                tempUpReg("80500201", "0x" + (tempVal | 0x02).ToString("x2"));
                            }
                            if (string.IsNullOrEmpty(gpio8_15_dir))
                            {
                                tempList.Add(new string[3] { "0x0205,0x00,", null, null });
                            }
                            else
                            {
                                uint tempVal = Convert.ToUInt16(gpio8_15_dir, 16);
                                tempUpReg("80500205", "0x" + (tempVal & 0xfd).ToString("x2"));
                            }
                            if (string.IsNullOrEmpty(gpio8_15_in_en))
                            {
                                tempList.Add(new string[3] { "0x00d1,0x02,", null, null });
                            }
                            else
                            {
                                uint tempVal = Convert.ToUInt16(gpio8_15_in_en, 16);
                                tempUpReg("805000d1", "0x" + (tempVal | 0x02).ToString("x2"));
                            }
                            break;
                        case 3://Gpio 22
                            string gpio16_23_en = tempList.LastOrDefault(c => c[1] == "80500202")?.GetValue(2).ToString();
                            string gpio16_23_dir = tempList.LastOrDefault(c => c[1] == "80500206")?.GetValue(2).ToString();
                            string gpio16_23_in_en = tempList.LastOrDefault(c => c[1] == "805000d2")?.GetValue(2).ToString();
                            int x = tempList.FindLastIndex(c => c[1] == "805000d2");
                            if (string.IsNullOrEmpty(gpio16_23_en) || string.IsNullOrEmpty(gpio16_23_dir) || string.IsNullOrEmpty(gpio16_23_in_en))
                            {
                                tempList.Add(new string[3] { "0xfffd,0x80,\r\n0xfffe,0x50,", null, null });
                            }
                            if (string.IsNullOrEmpty(gpio16_23_en))
                            {
                                tempList.Add(new string[3] { "0x0202,0x40,", null, null });
                            }
                            else
                            {
                                uint tempVal = Convert.ToUInt16(gpio16_23_en, 16);
                                tempUpReg("80500202", "0x" + (tempVal | 0x40).ToString("x2"));
                            }
                            if (string.IsNullOrEmpty(gpio16_23_dir))
                            {
                                tempList.Add(new string[3] { "0x0206,0x00,", null, null });
                            }
                            else
                            {
                                uint tempVal = Convert.ToUInt16(gpio16_23_dir, 16);
                                tempUpReg("80500206", "0x" + (tempVal & 0xbf).ToString("x2"));
                            }
                            if (string.IsNullOrEmpty(gpio16_23_in_en))
                            {
                                tempList.Add(new string[3] { "0x00d2,0x40,", null, null });
                            }
                            else
                            {
                                uint tempVal = Convert.ToUInt16(gpio16_23_in_en, 16);
                                tempUpReg("805000d2", "0x" + (tempVal | 0x40).ToString("x2"));
                            }
                            break;
                        #endregion
                        default:
                            break;
                    }
                    rList = tempList.Select(c => c[0]).ToList();
                }
                else if (_isPress_key == 1)
                {
                    rList.AddRange(ParaHelp.CreateBinADC());
                }
            }
            else
            {
                //添加轮询使能开关
                rList.Add("0xfffd,0x80,");
                rList.Add("0xfffe,0x14,");
                rList.Add("0x0b1e,0x00,");
            }
            //if (!isoSwitchingcheck.Checked)
            //{
            rList.AddRange(ParaHelp.CreateBinSwitchingPatch());
            //}

            rList.Add("");
            rList.AddRange(ParaHelp.CreateBinTaoshiUtc());
            if (_isOsdVerCheck)
            {
                rList.AddRange(ParaHelp.CreateOsdVersionInfo());
            }
            string openpath = System.IO.Path.GetDirectoryName(pSavePath) + "\\Temp_" + Path.GetFileNameWithoutExtension(pLocalName) + ".txt";
            File.WriteAllLines(openpath, rList.ToArray());
            Setting2Help.FlashSetting2Flash(openpath, path, 1, 0, 0); //测试模式下 Usage FPGA  选择0； --东东发布的时候改 现在这个给你用
            return path;
        }

        /// <summary>
        /// 打开文件
        /// </summary>
        /// <param name="openFile">文件路径</param>
        /// <returns></returns>
        public string OpenSettingToFile(string openFile, bool _isPollingSetOk, bool _isOsdTemp, bool _isOsdVerCheck)
        {
            string pSavePath = string.Format("{0}\\Lib\\xc{1}_setting\\", Application.StartupPath, ConfigurationManager.AppSettings["xcVersion"]);
            string pLocalName = System.IO.Path.GetFileName(openFile); //获取文件名
            string path = pSavePath + "\\Flash_" + Path.GetFileNameWithoutExtension(pLocalName) + ".txt";

            //增加是否有轮询
            var rList = Setting2Help.ReadTextFileToList(openFile);
            if (_isPollingSetOk)
            {
                rList.AddRange(ParaHelp.CreateBinPressKey());
                uint pin = Convert.ToUInt16(ParaHelp.Bin_Press_Key.Find(p => p.PKey == "0x0b38").PValue, 16);
                List<string[]> tempList = new List<string[]>();
                #region 解析rlist存入tempList
                string addrPageH = "80";
                string addrPageM = string.Empty;
                foreach (string line in rList)
                {
                    string[] temp = new string[3];
                    temp[0] = line;
                    string[] col = line.ToLower().Replace('，', ',').Split(',');
                    string colFirst = col.First().Trim();
                    if (col.Count() > 2)
                    {
                        if (colFirst == "0xfffd")
                        {
                            addrPageH = col[1].Replace("0x", "").Trim();
                        }
                        else if (colFirst == "0xfffe")
                        {
                            addrPageM = col[1].Replace("0x", "").Trim();
                        }
                        else if (colFirst.Contains("0x") && !colFirst.Contains("//"))
                        {
                            temp[1] = addrPageH + addrPageM + colFirst.Replace("0x", "").Replace(" ", "");
                            temp[2] = col[1].Replace("0x", "").Replace(" ", "");
                        }
                    }
                    tempList.Add(temp);
                }
                #endregion
                #region 更新寄存器方法
                Action<string, string> tempUpReg = new Action<string, string>(
                             (string addr, string value) =>
                             {
                                 string tempstr = tempList.LastOrDefault(c => c[1] == addr).First();
                                 string[] tempStrArray = tempstr.Replace("，", ",").Split(',');
                                 tempStrArray[1] = value;
                                 tempList.Last(c => c[1] == addr)[0] = string.Join(",", tempStrArray);
                             });
                #endregion
                string gpio8_15_en = tempList.LastOrDefault(c => c[1] == "80500201")?.GetValue(2).ToString();
                string gpio8_15_dir = tempList.LastOrDefault(c => c[1] == "80500205")?.GetValue(2).ToString();
                string gpio8_15_in_en = tempList.LastOrDefault(c => c[1] == "805000d1")?.GetValue(2).ToString();
                switch (pin)
                {
                    #region 更新按键轮询所选gpio相关寄存器
                    case 0://Gpio 2
                        string gpio0_7_en = tempList.LastOrDefault(c => c[1] == "80500200")?.GetValue(2).ToString();
                        string gpio0_7_dir = tempList.LastOrDefault(c => c[1] == "80500204")?.GetValue(2).ToString();
                        string gpio0_7_in_en = tempList.LastOrDefault(c => c[1] == "805000d0")?.GetValue(2).ToString();
                        if (string.IsNullOrEmpty(gpio0_7_en) || string.IsNullOrEmpty(gpio0_7_dir) || string.IsNullOrEmpty(gpio0_7_in_en))
                        {
                            tempList.Add(new string[3] { "0xfffd,0x80,\r\n0xfffe,0x50,", null, null });
                        }
                        if (string.IsNullOrEmpty(gpio0_7_en))
                        {
                            tempList.Add(new string[3] { "0x0200,0x04,", null, null });
                        }
                        else
                        {
                            uint tempVal = Convert.ToUInt16(gpio0_7_en, 16);
                            tempUpReg("80500200", "0x" + (tempVal | 0x04).ToString("x2"));
                        }
                        if (string.IsNullOrEmpty(gpio0_7_dir))
                        {
                            tempList.Add(new string[3] { "0x0204,0x00,", null, null });
                        }
                        else
                        {
                            uint tempVal = Convert.ToUInt16(gpio0_7_dir, 16);
                            tempUpReg("80500204", "0x" + (tempVal & 0xfb).ToString("x2"));
                        }
                        if (string.IsNullOrEmpty(gpio0_7_in_en))
                        {
                            tempList.Add(new string[3] { "0x00d0,0x04,", null, null });
                        }
                        else
                        {
                            uint tempVal = Convert.ToUInt16(gpio0_7_in_en, 16);
                            tempUpReg("805000d0", "0x" + (tempVal | 0x04).ToString("x2"));
                        }
                        break;
                    case 1://Gpio 8                           
                        if (string.IsNullOrEmpty(gpio8_15_en) || string.IsNullOrEmpty(gpio8_15_dir) || string.IsNullOrEmpty(gpio8_15_in_en))
                        {
                            tempList.Add(new string[3] { "0xfffd,0x80,\r\n0xfffe,0x50,", null, null });
                        }
                        if (string.IsNullOrEmpty(gpio8_15_en))
                        {
                            tempList.Add(new string[3] { "0x0201,0x01,", null, null });
                        }
                        else
                        {
                            uint tempVal = Convert.ToUInt16(gpio8_15_en, 16);
                            tempUpReg("80500201", "0x" + (tempVal | 0x01).ToString("x2"));
                        }
                        if (string.IsNullOrEmpty(gpio8_15_dir))
                        {
                            tempList.Add(new string[3] { "0x0205,0x00,", null, null });
                        }
                        else
                        {
                            uint tempVal = Convert.ToUInt16(gpio8_15_dir, 16);
                            tempUpReg("80500205", "0x" + (tempVal & 0xfe).ToString("x2"));
                        }
                        if (string.IsNullOrEmpty(gpio8_15_in_en))
                        {
                            tempList.Add(new string[3] { "0x00d1,0x01,", null, null });
                        }
                        else
                        {
                            uint tempVal = Convert.ToUInt16(gpio8_15_in_en, 16);
                            tempUpReg("805000d1", "0x" + (tempVal | 0x01).ToString("x2"));
                        }
                        break;
                    case 2://Gpio 9
                        if (string.IsNullOrEmpty(gpio8_15_en) || string.IsNullOrEmpty(gpio8_15_dir) || string.IsNullOrEmpty(gpio8_15_in_en))
                        {
                            tempList.Add(new string[3] { "0xfffd,0x80,\r\n0xfffe,0x50,", null, null });
                        }
                        if (string.IsNullOrEmpty(gpio8_15_en))
                        {
                            tempList.Add(new string[3] { "0x0201,0x02,", null, null });
                        }
                        else
                        {
                            uint tempVal = Convert.ToUInt16(gpio8_15_en, 16);
                            tempUpReg("80500201", "0x" + (tempVal | 0x02).ToString("x2"));
                        }
                        if (string.IsNullOrEmpty(gpio8_15_dir))
                        {
                            tempList.Add(new string[3] { "0x0205,0x00,", null, null });
                        }
                        else
                        {
                            uint tempVal = Convert.ToUInt16(gpio8_15_dir, 16);
                            tempUpReg("80500205", "0x" + (tempVal & 0xfd).ToString("x2"));
                        }
                        if (string.IsNullOrEmpty(gpio8_15_in_en))
                        {
                            tempList.Add(new string[3] { "0x00d1,0x02,", null, null });
                        }
                        else
                        {
                            uint tempVal = Convert.ToUInt16(gpio8_15_in_en, 16);
                            tempUpReg("805000d1", "0x" + (tempVal | 0x02).ToString("x2"));
                        }
                        break;
                    case 3://Gpio 22
                        string gpio16_23_en = tempList.LastOrDefault(c => c[1] == "80500202")?.GetValue(2).ToString();
                        string gpio16_23_dir = tempList.LastOrDefault(c => c[1] == "80500206")?.GetValue(2).ToString();
                        string gpio16_23_in_en = tempList.LastOrDefault(c => c[1] == "805000d2")?.GetValue(2).ToString();
                        int x = tempList.FindLastIndex(c => c[1] == "805000d2");
                        if (string.IsNullOrEmpty(gpio16_23_en) || string.IsNullOrEmpty(gpio16_23_dir) || string.IsNullOrEmpty(gpio16_23_in_en))
                        {
                            tempList.Add(new string[3] { "0xfffd,0x80,\r\n0xfffe,0x50,", null, null });
                        }
                        if (string.IsNullOrEmpty(gpio16_23_en))
                        {
                            tempList.Add(new string[3] { "0x0202,0x40,", null, null });
                        }
                        else
                        {
                            uint tempVal = Convert.ToUInt16(gpio16_23_en, 16);
                            tempUpReg("80500202", "0x" + (tempVal | 0x40).ToString("x2"));
                        }
                        if (string.IsNullOrEmpty(gpio16_23_dir))
                        {
                            tempList.Add(new string[3] { "0x0206,0x00,", null, null });
                        }
                        else
                        {
                            uint tempVal = Convert.ToUInt16(gpio16_23_dir, 16);
                            tempUpReg("80500206", "0x" + (tempVal & 0xbf).ToString("x2"));
                        }
                        if (string.IsNullOrEmpty(gpio16_23_in_en))
                        {
                            tempList.Add(new string[3] { "0x00d2,0x40,", null, null });
                        }
                        else
                        {
                            uint tempVal = Convert.ToUInt16(gpio16_23_in_en, 16);
                            tempUpReg("805000d2", "0x" + (tempVal | 0x40).ToString("x2"));
                        }
                        break;
                    #endregion
                    default:
                        break;
                }
                rList = tempList.Select(c => c[0]).ToList();
            }
            else
            {
                //添加轮询使能开关
                rList.Add("0xfffd,0x80,");
                rList.Add("0xfffe,0x14,");
                rList.Add("0x0b1e,0x00,");
            }
            if (_isOsdTemp)
            {
                rList.Add($"0xfffe,0x14,");
                rList.Add($"0x08a6,0x01,//温度显示使能开关");
            }
            if (_isOsdVerCheck)
            {
                rList.AddRange(ParaHelp.CreateOsdVersionInfo());
            }

            string openpath = System.IO.Path.GetDirectoryName(pSavePath) + "\\Temp_" + Path.GetFileNameWithoutExtension(pLocalName) + ".txt";
            File.WriteAllLines(openpath, rList.ToArray());
            Setting2Help.FlashSetting2Flash(openpath, path, 1, 0, 0); //测试模式下 Usage FPGA  选择0； --东东发布的时候改 现在这个给你用
            return path;
        }

        private void barButtonItem4_ItemClick_2(object sender, DevExpress.XtraBars.ItemClickEventArgs e)
        {
            if (navigationFrame.Pages.Any(c => c.Caption == "page_HDR"))
            {
                //navigationFrame.SelectedPageIndex = navigationFrame.Pages.FindIndex(c => c.Caption == "page_HDR");
                navigationFrame.SelectedPage = (INavigationPage)navigationFrame.Pages.FindFirst(c => c.Caption == "page_HDR");

                xChip_HDR.sPortTemp = sPortTemp;
            }
            else
            {
                this.splashScreenManager1.ShowWaitForm();
                NavigationPage page = new NavigationPage();
                xChip_HDR = XChip_Lite_HDR.Instance(sPortTemp, addressregisterBll);
                xChip_HDR.Dock = DockStyle.Fill;
                xChip_HDR.sPortTemp = sPortTemp;
                page.Controls.Add(xChip_HDR);
                page.Name = "page_HDR";
                navigationFrame.Pages.Add(page);
                navigationFrame.SelectedPage = page;
                this.splashScreenManager1.CloseWaitForm();
            }
            //SetOpenSport();
            //navigationFrame.SelectedPage = Page_Hdr;
        }

        private void barButtonItem5_ItemClick_1(object sender, DevExpress.XtraBars.ItemClickEventArgs e)
        {
            if (navigationFrame.Pages.Any(c => c.Caption == "page_SNR"))
            {
                //navigationFrame.SelectedPageIndex = navigationFrame.Pages.FindIndex(c => c.Caption == "page_SNR");
                navigationFrame.SelectedPage = (INavigationPage)navigationFrame.Pages.FindFirst(c => c.Caption == "page_SNR");

                xChip_Reg_Snr.sPortTemp = sPortTemp;
            }
            else
            {
                this.splashScreenManager1.ShowWaitForm();
                NavigationPage page = new NavigationPage();
                xChip_Reg_Snr = new XChip_Lite_Snr(sPortTemp, addressregisterBll);
                xChip_Reg_Snr.Dock = DockStyle.Fill;
                xChip_Reg_Snr.sPortTemp = sPortTemp;
                page.Controls.Add(xChip_Reg_Snr);
                page.Name = "page_SNR";
                navigationFrame.Pages.Add(page);
                navigationFrame.SelectedPage = page;
                this.splashScreenManager1.CloseWaitForm();
            }
            //对USB开关赋值
            USBSwitch();
            //navigationFrame.SelectedPage = Page_Snr;
        }

        private void barButtonItem9_ItemClick_1(object sender, DevExpress.XtraBars.ItemClickEventArgs e)
        {
            if (navigationFrame.Pages.Any(c => c.Caption == "page_CFA"))
            {
                //navigationFrame.SelectedPageIndex = navigationFrame.Pages.FindIndex(c => c.Caption == "page_CFA");
                navigationFrame.SelectedPage = (INavigationPage)navigationFrame.Pages.FindFirst(c => c.Caption == "page_CFA");

                xChip_Reg_Cfa.sPortTemp = sPortTemp;
            }
            else
            {
                this.splashScreenManager1.ShowWaitForm();
                NavigationPage page = new NavigationPage();
                xChip_Reg_Cfa = new XChip_Lite_Cfa(sPortTemp, addressregisterBll);
                xChip_Reg_Cfa.Dock = DockStyle.Fill;
                xChip_Reg_Cfa.sPortTemp = sPortTemp;
                page.Controls.Add(xChip_Reg_Cfa);
                page.Name = "page_CFA";
                navigationFrame.Pages.Add(page);
                navigationFrame.SelectedPage = page;
                this.splashScreenManager1.CloseWaitForm();
            }
            //navigationFrame.SelectedPage = Page_Cfa;
        }

        private void barButtonItem14_ItemClick_1(object sender, DevExpress.XtraBars.ItemClickEventArgs e)
        {
            //navigationFrame.SelectedPage = Page_Cnr;
        }

        private void barButtonItem10_ItemClick_1(object sender, DevExpress.XtraBars.ItemClickEventArgs e)
        {
            if (navigationFrame.Pages.Any(c => c.Caption == "page_YNR_CNR"))
            {
                //navigationFrame.SelectedPageIndex = navigationFrame.Pages.FindIndex(c => c.Caption == "page_YNR_CNR");
                navigationFrame.SelectedPage = (INavigationPage)navigationFrame.Pages.FindFirst(c => c.Caption == "page_YNR_CNR");

                xChip_Reg_Ynr.sPortTemp = sPortTemp;
            }
            else
            {
                this.splashScreenManager1.ShowWaitForm();
                NavigationPage page = new NavigationPage();
                xChip_Reg_Ynr = new XChip_Lite_Ynr(sPortTemp, addressregisterBll);
                xChip_Reg_Ynr.Dock = DockStyle.Fill;
                xChip_Reg_Ynr.sPortTemp = sPortTemp;
                page.Controls.Add(xChip_Reg_Ynr);
                page.Name = "page_YNR_CNR";
                navigationFrame.Pages.Add(page);
                navigationFrame.SelectedPage = page;
                this.splashScreenManager1.CloseWaitForm();
            }
            //navigationFrame.SelectedPage = Page_Ynr;
        }

        private void barButtonItem13_ItemClick_1(object sender, DevExpress.XtraBars.ItemClickEventArgs e)
        {
            if (navigationFrame.Pages.Any(c => c.Caption == "page_YDE"))
            {
                //navigationFrame.SelectedPageIndex = navigationFrame.Pages.FindIndex(c => c.Caption == "page_YDE");
                navigationFrame.SelectedPage = (INavigationPage)navigationFrame.Pages.FindFirst(c => c.Caption == "page_YDE");

                xChip_Reg_Yde.sPortTemp = sPortTemp;
            }
            else
            {
                this.splashScreenManager1.ShowWaitForm();
                NavigationPage page = new NavigationPage();
                xChip_Reg_Yde = new XChip_Lite_Yde(sPortTemp, addressregisterBll);
                xChip_Reg_Yde.Dock = DockStyle.Fill;
                xChip_Reg_Yde.sPortTemp = sPortTemp;
                page.Controls.Add(xChip_Reg_Yde);
                page.Name = "page_YDE";
                navigationFrame.Pages.Add(page);
                navigationFrame.SelectedPage = page;
                this.splashScreenManager1.CloseWaitForm();
            }
            //navigationFrame.SelectedPage = Page_Yde;
        }

        private void barButtonItem17_ItemClick_1(object sender, DevExpress.XtraBars.ItemClickEventArgs e)
        {
            if (navigationFrame.Pages.Any(c => c.Caption == "page_FCC"))
            {
                //navigationFrame.SelectedPageIndex = navigationFrame.Pages.FindIndex(c => c.Caption == "page_FCC");
                navigationFrame.SelectedPage = (INavigationPage)navigationFrame.Pages.FindFirst(c => c.Caption == "page_FCC");

                xChip_Reg_FCC.sPortTemp = sPortTemp;
            }
            else
            {
                this.splashScreenManager1.ShowWaitForm();
                NavigationPage page = new NavigationPage();
                xChip_Reg_FCC = new XChip_Reg_FCC(sPortTemp, addressregisterBll);
                xChip_Reg_FCC.Dock = DockStyle.Fill;
                xChip_Reg_FCC.sPortTemp = sPortTemp;
                page.Controls.Add(xChip_Reg_FCC);
                page.Name = "page_FCC";
                navigationFrame.Pages.Add(page);
                navigationFrame.SelectedPage = page;
                this.splashScreenManager1.CloseWaitForm();
            }
            //navigationFrame.SelectedPage = Page_Fcc;
        }

        private void barButtonItem19_ItemClick_1(object sender, DevExpress.XtraBars.ItemClickEventArgs e)
        {
            Task.Factory.StartNew(() => {
                XChip_CameraControl xc_camera = new XChip_CameraControl();
                xc_camera.ShowDialog();
            });

        }
        /// <summary>
        /// bin解析测试
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void barButtonItem23_ItemClick(object sender, DevExpress.XtraBars.ItemClickEventArgs e)
        {
            binTestForm bintestform = new binTestForm();
            bintestform.StartPosition = FormStartPosition.CenterParent;
            bintestform.ShowDialog();
        }
        //判断是否按寄存器值排列还是按一条八个字节排列
        public void filePathSetting(List<BinBase> blist, string name, bool isaddr)
        {
            //var ccccc = blist.Where(c => c.note != null && c.note.Contains(name)).ToList();
            // string desktopPath = Environment.GetFolderPath(Environment.SpecialFolder.Desktop);
            // string filePath = Path.Combine(desktopPath, $"{name}.txt");
            // if (isaddr)
            // {
            //     using (StreamWriter writer = new StreamWriter(filePath))
            //     {
            //         //for (int i = 0; i < ccccc.Count(); i++)
            //         //{
            //         //    writer.WriteLine(ccccc[i].bigdata + ccccc[i].bigaddr);
            //         //    i += 3;
            //         //}
            //     }
            // }
            // else
            // {
            //     using (StreamWriter writer = new StreamWriter(filePath))
            //     {

            //         for (int i = 0; i < ccccc.Count(); i++)
            //         {
            //             if (ccccc[i].bigaddr == "F5F5" || ccccc[i].bigaddr == "F5FF")
            //             {
            //                 writer.WriteLine();
            //                 writer.WriteLine("crc:" + ccccc[i].bigaddr + blist[i].bigdata);
            //                 writer.WriteLine();
            //             }
            //             else
            //             {
            //                 writer.WriteLine(ccccc[i].smallexample.ToLower());
            //             }
            //             i += 3;
            //         }
            //     }
            // }

        }


        public void addnote(List<BinBase> blist, string terms)
        {
            #region 区域注释添加
            var Enablelist = blist.Where(c => c.original == 0x01 && c.note != null && c.note.Contains("_en")).ToList();

            var listEn = Enablelist.Where(c => c.original == 0x01 && c.describe != null && c.note.Contains(terms)).ToList();
            for (int i = 0; i < listEn.Count(); i++)
            {
                //已使能的文件首地址
                var listenable = blist.FindIndex(c => c.describe != null && c.note != null && c.note.Contains(listEn[i].note.Replace("_en", "")) && c.describe.Contains("首地址"));
                //文件地址
                var listaddr = Convert.ToInt32(blist[listenable + 3].original.ToString("X") + blist[listenable + 2].original.ToString("X") + blist[listenable + 1].original.ToString("X") + blist[listenable].original.ToString("X"), 16);

                //文件长度
                var listlength = Convert.ToInt32(blist[listaddr + 7].original.ToString("X") + blist[listaddr + 6].original.ToString("X") + blist[listaddr + 5].original.ToString("X") + blist[listaddr + 4].original.ToString("X"), 16);
                //crc区域长度
                int crclength = 8;
                //乘4的原因是文件长度表示的是4个为一组的寄存器加值的格式所以要得出正确的长度需要乘4
                for (int j = listaddr; j < listaddr + (listlength * 4); j++)
                {
                    //前八字节的crc校验
                    if (blist[j].original == 0xF5 && blist[j + 1].original == 0xFF)
                    {
                        //j是0xF5的索引应该-2得到crc索引
                        if (crclength == 8)
                        {
                            for (int c = j - 2; c <= j + 1; c++)
                            {
                                blist[c].describe = "crc";
                                blist[c].remarks = $"{listEn[i].note.Replace("_en", "")}crc";
                                blist[c].crcold = blist[j - 2].original.ToString("X") + blist[j - 1].original.ToString("X") + blist[j].original.ToString("X") + blist[j + 1].original.ToString("X");
                                blist[c].crchead = listaddr.ToString();
                                blist[c].crctail = (j - 3).ToString();
                                blist[c].crclength = crclength.ToString();
                                blist[c].module = $"{listEn[i].note.Replace("_en", "")}";
                                blist[c].note = $"{listEn[i].note.Replace("_en", "")}crc";

                            }
                            crclength = 128;
                        }
                        j += 2;
                    }
                    else if (blist[j].original == 0xF5 && blist[j + 1].original == 0xF5)
                    {
                        for (int c = j - 2; c <= j + 1; c++)
                        {
                            blist[c].describe = "crc";
                            blist[c].remarks = $"{listEn[i].note.Replace("_en", "")}crc";
                            blist[c].crcold = blist[j - 2].original.ToString("X") + blist[j - 1].original.ToString("X") + blist[j].original.ToString("X") + blist[j + 1].original.ToString("X");
                            blist[c].crchead = (j + 2).ToString();
                            blist[c].crctail = (j + 2 + crclength).ToString();
                            blist[c].crclength = crclength.ToString();
                            blist[c].module = $"{listEn[i].note.Replace("_en", "")}";
                            blist[c].note = $"{listEn[i].note.Replace("_en", "")}crc";
                        }
                        j += 2;
                    }
                    else
                    {
                        blist[j].module = $"{listEn[i].note.Replace("_en", "")}";
                        blist[j].note = $"{listEn[i].note.Replace("_en", "")}数据";
                    }

                }
            }

            #endregion
        }

        private void barButtonItem27_ItemClick(object sender, DevExpress.XtraBars.ItemClickEventArgs e)
        {
            if (navigationFrame.Pages.Any(c => c.Caption == "page_LENC"))
            {
                //navigationFrame.SelectedPageIndex = navigationFrame.Pages.FindIndex(c => c.Caption == "page_LENC");
                navigationFrame.SelectedPage = (INavigationPage)navigationFrame.Pages.FindFirst(c => c.Caption == "page_LENC");

                //xChip_LENC.sPortTemp = sPortTemp;
            }
            else
            {
                this.splashScreenManager1.ShowWaitForm();
                NavigationPage page = new NavigationPage();
                xChip_LENC = new XChip_LENC(sPortTemp, addressregisterBll, Pe_patch_dal, Pe_dal);
                xChip_LENC.Dock = DockStyle.Fill;
                //xChip_LENC.sPortTemp = sPortTemp;
                page.Controls.Add(xChip_LENC);
                page.Name = "page_LENC";
                navigationFrame.Pages.Add(page);
                navigationFrame.SelectedPage = page;
                this.splashScreenManager1.CloseWaitForm();
            }
            //对USB开关赋值
            USBSwitch();
        }

        private void barButtonItem34_ItemClick(object sender, DevExpress.XtraBars.ItemClickEventArgs e)
        {
            if (navigationFrame.Pages.Any(c => c.Caption == "page_CFA"))
            {
                //navigationFrame.SelectedPageIndex = navigationFrame.Pages.FindIndex(c => c.Caption == "page_CFA");
                navigationFrame.SelectedPage = (INavigationPage)navigationFrame.Pages.FindFirst(c => c.Caption == "page_CFA");

                xChip_Reg_Cfa.sPortTemp = sPortTemp;
            }
            else
            {
                this.splashScreenManager1.ShowWaitForm();
                NavigationPage page = new NavigationPage();
                xChip_Reg_Cfa = new XChip_Lite_Cfa(sPortTemp, addressregisterBll);
                xChip_Reg_Cfa.Dock = DockStyle.Fill;
                xChip_Reg_Cfa.sPortTemp = sPortTemp;
                page.Controls.Add(xChip_Reg_Cfa);
                page.Name = "page_CFA";
                navigationFrame.Pages.Add(page);
                navigationFrame.SelectedPage = page;
                this.splashScreenManager1.CloseWaitForm();
            }
            //对USB开关赋值
            USBSwitch();
            //navigationFrame.SelectedPage = Page_Cfa;
        }

        private void barButtonItem26_ItemClick(object sender, DevExpress.XtraBars.ItemClickEventArgs e)
        {
            if (navigationFrame.Pages.Any(c => c.Caption == "page_CMX"))
            {
                //navigationFrame.SelectedPageIndex = navigationFrame.Pages.FindIndex(c => c.Caption == "page_CMX");
                navigationFrame.SelectedPage = (INavigationPage)navigationFrame.Pages.FindFirst(c => c.Caption == "page_CMX");

                xChip_CMX.sPortTemp = sPortTemp;
            }
            else
            {
                this.splashScreenManager1.ShowWaitForm();
                NavigationPage page = new NavigationPage();
                xChip_CMX = new XChip_Lite_CMX(sPortTemp, addressregisterBll);
                xChip_CMX.Dock = DockStyle.Fill;
                //xChip_AWB.sPortTemp = sPortTemp;
                page.Controls.Add(xChip_CMX);
                page.Name = "page_CMX";
                navigationFrame.Pages.Add(page);
                navigationFrame.SelectedPage = page;
                this.splashScreenManager1.CloseWaitForm();
            }
            //对USB开关赋值
            USBSwitch();
        }

        private void barButtonItem25_ItemClick(object sender, DevExpress.XtraBars.ItemClickEventArgs e)
        {
            if (navigationFrame.Pages.Any(c => c.Caption == "page_AWB"))
            {
                //navigationFrame.SelectedPageIndex = navigationFrame.Pages.FindIndex(c => c.Caption == "page_AWB");
                navigationFrame.SelectedPage = (INavigationPage)navigationFrame.Pages.FindFirst(c => c.Caption == "page_AWB");

                xChip_AWB.sPortTemp = sPortTemp;

            }
            else
            {
                this.splashScreenManager1.ShowWaitForm();
                NavigationPage page = new NavigationPage();
                xChip_AWB = new XChip_Lite_AWB(sPortTemp, addressregisterBll);
                xChip_AWB.Dock = DockStyle.Fill;
                //xChip_AWB.sPortTemp = sPortTemp;
                page.Controls.Add(xChip_AWB);
                page.Name = "page_AWB";
                navigationFrame.Pages.Add(page);
                navigationFrame.SelectedPage = page;
                this.splashScreenManager1.CloseWaitForm();

            }
            //对USB开关赋值
            USBSwitch();
            //SetOpenSport();
            //navigationFrame.SelectedPageIndex = 1;
            //officeNavigationBar.SelectedItem = navigationBarItem2;   
        }

        private void barButtonItem28_ItemClick(object sender, DevExpress.XtraBars.ItemClickEventArgs e)
        {
            if (navigationFrame.Pages.Any(c => c.Caption == "page_CADJ"))
            {
                //navigationFrame.SelectedPageIndex = navigationFrame.Pages.FindIndex(c => c.Caption == "page_CADJ");
                navigationFrame.SelectedPage = (INavigationPage)navigationFrame.Pages.FindFirst(c => c.Caption == "page_CADJ");

                xChip_CADJ.sPortTemp = sPortTemp;
            }
            else
            {
                WaitBefore.Start("请耐心等待...", "正在努力工作中");
                NavigationPage page = new NavigationPage();
                xChip_CADJ = new XChip_CADJ_C(sPortTemp, addressregisterBll);
                xChip_CADJ.Dock = DockStyle.Fill;
                xChip_CADJ.sPortTemp = sPortTemp;
                page.Controls.Add(xChip_CADJ);
                page.Name = "page_CADJ";
                navigationFrame.Pages.Add(page);
                navigationFrame.SelectedPage = page;
                WaitBefore.Close();
            }
            //对USB开关赋值
            USBSwitch();
            //SetOpenSport();
            //navigationFrame.SelectedPage = page_CADJ;
            //officeNavigationBar.SelectedItem = null;
        }

        private void barButtonItem29_ItemClick(object sender, DevExpress.XtraBars.ItemClickEventArgs e)
        {

            if (navigationFrame.Pages.Any(c => c.Caption == "page_AE"))
            {
                //navigationFrame.SelectedPageIndex = navigationFrame.Pages.FindIndex(c => c.Caption == "page_AE");
                navigationFrame.SelectedPage = (INavigationPage)navigationFrame.Pages.FindFirst(c => c.Caption == "page_AE");

            }
            //对USB开关赋值
            USBSwitch();
        }

        private void barButtonItem30_ItemClick(object sender, DevExpress.XtraBars.ItemClickEventArgs e)
        {
            if (navigationFrame.Pages.Any(c => c.Caption == "page_GAMMA"))
            {
                //navigationFrame.SelectedPageIndex = navigationFrame.Pages.FindIndex(c => c.Caption == "page_GAMMA");
                navigationFrame.SelectedPage = (INavigationPage)navigationFrame.Pages.FindFirst(c => c.Caption == "page_GAMMA");

                xChip_GAMMA.sPortTemp = sPortTemp;
            }
            else
            {
                this.splashScreenManager1.ShowWaitForm();
                NavigationPage page = new NavigationPage();
                xChip_GAMMA = XChip_GAMMA.Instance(sPortTemp, addressregisterBll);
                xChip_GAMMA.Dock = DockStyle.Fill;
                //xChip_GAMMA.sPortTemp = sPortTemp;
                page.Controls.Add(xChip_GAMMA);
                page.Name = "page_GAMMA";
                navigationFrame.Pages.Add(page);
                navigationFrame.SelectedPage = page;
                this.splashScreenManager1.CloseWaitForm();
            }
            //对USB开关赋值
            USBSwitch();
            //SetOpenSport();
            xChip_GAMMA.gammaM = new gammahistoryManager();
            //navigationFrame.SelectedPageIndex =5;
            //officeNavigationBar.SelectedItem = navigationBarItem6;

        }

        private void barButtonItem31_ItemClick(object sender, DevExpress.XtraBars.ItemClickEventArgs e)
        {
            if (navigationFrame.Pages.Any(c => c.Caption == "page_HDR"))
            {
                //navigationFrame.SelectedPageIndex = navigationFrame.Pages.FindIndex(c => c.Caption == "page_HDR");
                navigationFrame.SelectedPage = (INavigationPage)navigationFrame.Pages.FindFirst(c => c.Caption == "page_HDR");

                xChip_HDR.sPortTemp = sPortTemp;
            }
            else
            {
                this.splashScreenManager1.ShowWaitForm();
                NavigationPage page = new NavigationPage();
                xChip_HDR = XChip_Lite_HDR.Instance(sPortTemp, addressregisterBll);
                xChip_HDR.Dock = DockStyle.Fill;
                xChip_HDR.sPortTemp = sPortTemp;
                page.Controls.Add(xChip_HDR);
                page.Name = "page_HDR";
                navigationFrame.Pages.Add(page);
                navigationFrame.SelectedPage = page;
                this.splashScreenManager1.CloseWaitForm();
            }
            //对USB开关赋值
            USBSwitch();
            //SetOpenSport();
            //navigationFrame.SelectedPage = Page_Hdr;
        }

        private void barButtonItem32_ItemClick(object sender, DevExpress.XtraBars.ItemClickEventArgs e)
        {
            if (navigationFrame.Pages.Any(c => c.Caption == "page_DNR"))
            {
                //navigationFrame.SelectedPageIndex = navigationFrame.Pages.FindIndex(c => c.Caption == "page_DNR");
                navigationFrame.SelectedPage = (INavigationPage)navigationFrame.Pages.FindFirst(c => c.Caption == "page_DNR");

                xChip_DNS.sPortTemp = sPortTemp;
            }
            else
            {
                this.splashScreenManager1.ShowWaitForm();
                NavigationPage page = new NavigationPage();
                xChip_DNS = new XChip_Lite_DNR(sPortTemp, addressregisterBll);
                xChip_DNS.Dock = DockStyle.Fill;
                xChip_DNS.sPortTemp = sPortTemp;
                page.Controls.Add(xChip_DNS);
                page.Name = "page_DNR";
                navigationFrame.Pages.Add(page);
                navigationFrame.SelectedPage = page;
                this.splashScreenManager1.CloseWaitForm();
            }
            //对USB开关赋值
            USBSwitch();
        }

        private void barButtonItem33_ItemClick(object sender, DevExpress.XtraBars.ItemClickEventArgs e)
        {
            if (navigationFrame.Pages.Any(c => c.Caption == "page_DNR_CAL"))
            {
                //navigationFrame.SelectedPageIndex = navigationFrame.Pages.FindIndex(c => c.Caption == "page_DNR_CAL");
                navigationFrame.SelectedPage = (INavigationPage)navigationFrame.Pages.FindFirst(c => c.Caption == "page_DNR_CAL");

                xChip_DNR_CAL.sPortTemp = sPortTemp;
            }
            else
            {
                this.splashScreenManager1.ShowWaitForm();
                NavigationPage page = new NavigationPage();
                xChip_DNR_CAL = new XChip_DNR_CAL(sPortTemp, addressregisterBll);
                xChip_DNR_CAL.Dock = DockStyle.Fill;
                xChip_DNR_CAL.sPortTemp = sPortTemp;
                page.Controls.Add(xChip_DNR_CAL);
                page.Name = "page_DNR_CAL";
                navigationFrame.Pages.Add(page);
                navigationFrame.SelectedPage = page;
                this.splashScreenManager1.CloseWaitForm();
            }
            //对USB开关赋值
            USBSwitch();
            //SetOpenSport();
            //navigationFrame.SelectedPage = page_DNR_CAL;       
        }

        private void barButtonItem35_ItemClick(object sender, DevExpress.XtraBars.ItemClickEventArgs e)
        {
            if (navigationFrame.Pages.Any(c => c.Caption == "page_YNR_CNR"))
            {
                //navigationFrame.SelectedPageIndex = navigationFrame.Pages.FindIndex(c => c.Caption == "page_YNR_CNR");
                navigationFrame.SelectedPage = (INavigationPage)navigationFrame.Pages.FindFirst(c => c.Caption == "page_YNR_CNR");

                xChip_Reg_Ynr.sPortTemp = sPortTemp;
            }
            else
            {
                this.splashScreenManager1.ShowWaitForm();
                NavigationPage page = new NavigationPage();
                xChip_Reg_Ynr = new XChip_Lite_Ynr(sPortTemp, addressregisterBll);
                xChip_Reg_Ynr.Dock = DockStyle.Fill;
                xChip_Reg_Ynr.sPortTemp = sPortTemp;
                page.Controls.Add(xChip_Reg_Ynr);
                page.Name = "page_YNR_CNR";
                navigationFrame.Pages.Add(page);
                navigationFrame.SelectedPage = page;
                this.splashScreenManager1.CloseWaitForm();
            }
            //对USB开关赋值
            USBSwitch();
            //navigationFrame.SelectedPage = Page_Ynr;
        }

        private void barButtonItem36_ItemClick(object sender, DevExpress.XtraBars.ItemClickEventArgs e)
        {
            if (navigationFrame.Pages.Any(c => c.Caption == "page_YDE"))
            {
                //navigationFrame.SelectedPageIndex = navigationFrame.Pages.FindIndex(c => c.Caption == "page_YDE");
                navigationFrame.SelectedPage = (INavigationPage)navigationFrame.Pages.FindFirst(c => c.Caption == "page_YDE");

                xChip_Reg_Yde.sPortTemp = sPortTemp;
            }
            else
            {
                this.splashScreenManager1.ShowWaitForm();
                NavigationPage page = new NavigationPage();
                xChip_Reg_Yde = new XChip_Lite_Yde(sPortTemp, addressregisterBll);
                xChip_Reg_Yde.Dock = DockStyle.Fill;
                xChip_Reg_Yde.sPortTemp = sPortTemp;
                page.Controls.Add(xChip_Reg_Yde);
                page.Name = "page_YDE";
                navigationFrame.Pages.Add(page);
                navigationFrame.SelectedPage = page;
                this.splashScreenManager1.CloseWaitForm();
            }
            //对USB开关赋值
            USBSwitch();
            //navigationFrame.SelectedPage = Page_Yde;
        }

        private void barButtonItem37_ItemClick(object sender, DevExpress.XtraBars.ItemClickEventArgs e)
        {
            if (navigationFrame.Pages.Any(c => c.Caption == "page_SCENE"))
            {
                //navigationFrame.SelectedPageIndex = navigationFrame.Pages.FindIndex(c => c.Caption == "page_SCENE");
                navigationFrame.SelectedPage = (INavigationPage)navigationFrame.Pages.FindFirst(c => c.Caption == "page_SCENE");

                xChip_Scene_Switch.sPortTemp = sPortTemp;
            }
            else
            {
                this.splashScreenManager1.ShowWaitForm();
                NavigationPage page = new NavigationPage();
                xChip_Scene_Switch = new XChip_Lite_Scene_Switch(sPortTemp, addressregisterBll);
                xChip_Scene_Switch.Dock = DockStyle.Fill;
                xChip_Scene_Switch.sPortTemp = sPortTemp;
                page.Controls.Add(xChip_Scene_Switch);
                page.Name = "page_SCENE";
                navigationFrame.Pages.Add(page);
                navigationFrame.SelectedPage = page;
                this.splashScreenManager1.CloseWaitForm();
            }
            //对USB开关赋值
            USBSwitch();
            //SetOpenSport();
            //navigationFrame.SelectedPageIndex = 14;
            //officeNavigationBar.SelectedItem = null;
        }

        private void barButtonItem38_ItemClick(object sender, DevExpress.XtraBars.ItemClickEventArgs e)
        {
            if (navigationFrame.Pages.Any(c => c.Caption == "page_GPIO"))
            {
                //navigationFrame.SelectedPageIndex = navigationFrame.Pages.FindIndex(c => c.Caption == "page_GPIO");
                navigationFrame.SelectedPage = (INavigationPage)navigationFrame.Pages.FindFirst(c => c.Caption == "page_GPIO");

                xChip_Gpio.sPortTemp = sPortTemp;
            }
            else
            {
                WaitBefore.Start("请耐心等待...", "正在努力工作中");
                NavigationPage page = new NavigationPage();
                xChip_Gpio = new XChip_Gpio(sPortTemp, addressregisterBll);
                xChip_Gpio.Dock = DockStyle.Fill;
                xChip_Gpio.sPortTemp = sPortTemp;
                page.Controls.Add(xChip_Gpio);
                page.Name = "page_GPIO";
                navigationFrame.Pages.Add(page);
                navigationFrame.SelectedPage = page;
                WaitBefore.Close();
            }
            USBSwitch();
            //navigationFrame.SelectedPage = page_Gpio;
        }

        private void barButtonItem39_ItemClick(object sender, DevExpress.XtraBars.ItemClickEventArgs e)
        {
            if (navigationFrame.Pages.Any(c => c.Caption == "page_CRL"))
            {
                //navigationFrame.SelectedPageIndex = navigationFrame.Pages.FindIndex(c => c.Caption == "page_CRL");
                navigationFrame.SelectedPage = (INavigationPage)navigationFrame.Pages.FindFirst(c => c.Caption == "page_CRL");

                xChip_CRL.sPortTemp = sPortTemp;
            }
            else
            {
                WaitBefore.Start("请耐心等待...", "正在努力工作中");
                NavigationPage page = new NavigationPage();
                xChip_CRL = new XChip_CRL(sPortTemp, addressregisterBll);
                xChip_CRL.Dock = DockStyle.Fill;
                xChip_CRL.sPortTemp = sPortTemp;
                page.Controls.Add(xChip_CRL);
                page.Name = "page_CRL";
                navigationFrame.Pages.Add(page);
                navigationFrame.SelectedPage = page;
                WaitBefore.Close();
            }
            //对USB开关赋值
            USBSwitch();
            //SetOpenSport();
            //navigationFrame.SelectedPage = page_CRL;
            //officeNavigationBar.SelectedItem = null;
        }
        /// <summary>
        /// 用于切换串口USB切换
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void portusbBtn_Click(object sender, EventArgs e)
        {
            //IsSerial
            //AlignVerticalRight;Size16x16;Office2013  

            //if (portusbBtn.ImageOptions.ImageUri.Uri.Contains("AlignVerticalLeft"))
            //if (GetConfigValue("IsSerial") == "USB")
            //{
            //    portusbBtn.ImageOptions.ImageUri.Uri = "AlignVerticalRight;Size16x16;Office2013";
            //    PortControl.Hide();
            //    PortControl.Width = 0;
            //    UsbControl.Width = 167;
            //    RefreshUsb();
            //}
            //else
            //{
            //    portusbBtn.ImageOptions.ImageUri.Uri = "AlignVerticalLeft;Size16x16;Office2013";
            //    PortControl.Show();
            //    PortControl.Width = 167;
            //    UsbControl.Width = 0;
            //}

            //XChip_AeTest();
            XChip_AeTest2();
        }
        private string GetConfigValue(string strKey)
        {
            var configFile = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);
            var settings = configFile.AppSettings.Settings;

            return settings[strKey].Value;
        }
        /// <summary>
        /// 摄像头
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void simpleButton4_Click(object sender, EventArgs e)
        {
            Task.Factory.StartNew(() => {
                XChip_CameraControl xc_camera = new XChip_CameraControl();
                xc_camera.ShowDialog();
            });
        }
        /// <summary>
        /// 刷新设备
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnUsbRefresh_Click(object sender, EventArgs e)
        {
            if (!RefreshUsb())
            {
                MessageBox.Show("未获取到USB设备信息");
            };
        }

        private bool RefreshUsb()
        {
            try
            {

                int num = 0;
                //var selIndex = usbDevice.ItemIndex;
                IntPtr devicebool;
                if (IntPtr.Size == 8)
                {
                    XChipUSB.UsbIniDevice64();
                    XChipUSB.UsbUpdateDevice64();
                    num = XChipUSB.UsbGetDeviceNum64();
                    devicebool = XChipUSB.UsbGetAllDeviceInfo64();
                }
                else
                {
                    XChipUSB.UsbIniDevice86();
                    XChipUSB.UsbUpdateDevice86();
                    num = XChipUSB.UsbGetDeviceNum86();
                    devicebool = XChipUSB.UsbGetAllDeviceInfo86();
                }

                DeviceInfo[] deviceInfoArray = new DeviceInfo[num];
                for (int i = 0; i < deviceInfoArray.Length; i++)
                {
                    DeviceInfo deviceInfo = new DeviceInfo();
                    var one = (i * 120) * 2 + (i * 8);
                    deviceInfo.DevicePath = Marshal.PtrToStringAnsi(devicebool + one, 120);
                    var two = (i * 120) * 2 + 120 + (i * 8);
                    deviceInfo.DeviceName = Marshal.PtrToStringAnsi(devicebool + two, 120);
                    var three = (i * 120) * 2 + 240 + (i * 8);
                    deviceInfo.PID = Marshal.PtrToStringAnsi(devicebool + three, 4); // 读取内存中的 uint 值  
                    var four = (i * 120) * 2 + 240 + 4 + (i * 8);
                    deviceInfo.VID = Marshal.PtrToStringAnsi(devicebool + four, 4); // 读取内存中的 uint 值  
                    deviceInfoArray[i] = deviceInfo; // 将复制的数据添加到数组中  
                }
                string usbPath = string.Empty;
                if (USBDeviceHelp.UsbDev.Count(c => c.IsOpen == true) > 0)
                {
                    usbPath = USBDeviceHelp.UsbDev.Find(c => c.IsOpen == true).DevicePath;
                }

                USBDeviceHelp.UsbDev.Clear();
                //List<Enties.TreeListValue> list = new List<Enties.TreeListValue>();
                for (int i = 0; i < deviceInfoArray.Count(); i++)
                {
                    if (string.IsNullOrEmpty(deviceInfoArray[i].PID) || string.IsNullOrEmpty(deviceInfoArray[i].VID) || deviceInfoArray[i].PID == "\0\0\0\0" || deviceInfoArray[i].VID == "\0\0\0\0")
                    {
                        continue;
                    }
                    if (!string.IsNullOrEmpty(usbPath) && deviceInfoArray[i].DevicePath == usbPath)
                    {
                        USBDeviceHelp.UsbDev.Add(new USBDeviceModel() { DeviceName = deviceInfoArray[i].DeviceName, PID = deviceInfoArray[i].PID, VID = deviceInfoArray[i].VID, DevicePath = deviceInfoArray[i].DevicePath, Index = i, IsOpen = true });

                    }
                    else
                    {
                        USBDeviceHelp.UsbDev.Add(new USBDeviceModel() { DeviceName = deviceInfoArray[i].DeviceName, PID = deviceInfoArray[i].PID, VID = deviceInfoArray[i].VID, DevicePath = deviceInfoArray[i].DevicePath, Index = i, IsOpen = false });

                    }
                    //list.Add(new Enties.TreeListValue { ValueMember = $"{i}", DisplayMember = deviceInfoArray[i].DeviceName });
                }
                usbDevice.Properties.ValueMember = "DevicePath";
                usbDevice.Properties.DisplayMember = "DeviceName";
                usbDevice.Properties.DataSource = USBDeviceHelp.UsbDev;
                if (USBDeviceHelp.UsbDev.Count(c => c.IsOpen == true) > 0)
                {
                    usbDevice.ItemIndex = USBDeviceHelp.UsbDev.FindIndex(c => c.IsOpen == true);

                }
                else
                {
                    usbDevice.ItemIndex = 0;
                    USBDeviceHelp.UsbDev[0].IsOpen = true;
                }

                if (USBDeviceHelp.UsbDev.Count > 0)
                {
                    return true;
                }
                else
                {
                    return false;
                }
            }
            catch
            {
                return false;
            }
        }

        /// <summary>
        /// 打开Usb设备
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnUsb_Click(object sender, EventArgs e)
        {

            if (null == usbDevice || usbDevice.Text.ToString().Contains("请"))
            {
                MessageBox.Show("请选择USB设备！"); return;
            }
            //RefreshUsb();

            var index = USBDeviceHelp.UsbDev.FindIndex(c => c.DevicePath == USBItemIndex);
            if (index != -1 && btnUsb.Text.Contains("打开"))
            {


                if (IntPtr.Size == 8)
                {
                    XChipUSB.UsbIniDevice64();
                    XChipUSB.UsbUpdateDevice64();
                    IsUsbOpen = XChipUSB.UsbSelectDevice64(index);
                }
                else
                {
                    XChipUSB.UsbIniDevice86();
                    XChipUSB.UsbUpdateDevice86();
                    IsUsbOpen = XChipUSB.UsbSelectDevice86(index);
                }
                SerialPortHelperLib.SerialSend.IsUsbOpen = IsUsbOpen;
                USBSwitch();
                var d = SerialSend.ReadRegister(0x80500000, sPortTemp);
                var dd = SerialSend.ReadRegister(0x80500001, sPortTemp);
                
                if (d != 0x51 || dd != 0x01)
                {
                    setShowMsg("芯片ID有误！停止请求！");
                    IsUsbOpen = false;
                    setButtonUsbBackColor(btnUsb, false);
                    if (IntPtr.Size == 8)
                    {
                        XChipUSB.UsbUpdateDevice64();
                        //var t = XChipUSB.UsbDestroyUSB64();
                    }
                    else
                    {
                        XChipUSB.UsbUpdateDevice86();
                        //var t = XChipUSB.UsbDestroyUSB86();
                    }
                    USBDeviceHelp.UsbDev.ForEach(c =>
                    {

                        c.IsOpen = false;

                    });
                    IsUsbOpen = false;
                    USBSwitch();
                    return;
                }
                #region 验证bin密码
                var binH1 = SerialSend.ReadRegister(0x200018d0, sPortTemp).ToString("x2");
                var binH2 = SerialSend.ReadRegister(0x200018d1, sPortTemp).ToString("x2");
                var binH3 = SerialSend.ReadRegister(0x200018d2, sPortTemp).ToString("x2");
                var binH4 = SerialSend.ReadRegister(0x200018d3, sPortTemp).ToString("x2");
                if (SerialSend.ReadRegister(0x200018d4, sPortTemp).ToString("x2") == "00")
                {

                }
                else
                {
                    var temp1 = Convert.ToUInt32($"{binH1}{binH2}{binH3}{binH4}", 16);
                    var str = AppHelper.GetAppConfig("BinSecretKey");
                    var eee = AppHelper.XorNotEncryption(str);
                    if (eee != temp1)
                    {
                        IsUsbOpen = false;
                        setButtonUsbBackColor(btnUsb, false);
                        if (IntPtr.Size == 8)
                        {
                            XChipUSB.UsbUpdateDevice64();
                            //var t = XChipUSB.UsbDestroyUSB64();
                        }
                        else
                        {
                            XChipUSB.UsbUpdateDevice86();
                            //var t = XChipUSB.UsbDestroyUSB86();
                        }
                        USBDeviceHelp.UsbDev.ForEach(c =>
                        {

                            c.IsOpen = false;

                        });
                        IsUsbOpen = false;
                        USBSwitch();
                        DevExpress.XtraEditors.XtraMessageBox.Show("请输入正确的Bin密钥！");
                        return;
                    }
                }
                #endregion

                setButtonUsbBackColor(btnUsb, true);
                USBDeviceHelp.UsbDev.ForEach(c => {
                    if (c.DevicePath == USBItemIndex)
                    {
                        c.IsOpen = true;
                    }
                });
                //btnUsb.Text = "关闭";
                SetOpenSport();
            }
            else
            {
                IsUsbOpen = false;
                setButtonUsbBackColor(btnUsb, false);
                if (IntPtr.Size == 8)
                {
                    XChipUSB.UsbUpdateDevice64();
                    //var t = XChipUSB.UsbDestroyUSB64();
                }
                else
                {
                    XChipUSB.UsbUpdateDevice86();
                    //var t = XChipUSB.UsbDestroyUSB86();
                }
                USBDeviceHelp.UsbDev.ForEach(c => {

                    c.IsOpen = false;

                });
                USBSwitch();
                //btnUsb.Text = "打开";
            }
        }

        private void btn_Reset_Chip_Click(object sender, EventArgs e)
        {
            if (!sPortTemp.IsOpen && !IsUsbOpen && !m_open)//串口检测
            {
                DevExpress.XtraEditors.XtraMessageBox.Show("串口未打开");
                return;
            }
            if (IsUsbOpen)
            {
                SerialSend.WriteRegister(0x80500137, 0xce, sPortTemp);
            }
            else
            {
                SerialSend.WriteRegister(0x80500137, 0xd2, sPortTemp);
            }

        }

        //模拟单击事件
        private void XModemForm_OpenPortButtonClick(bool isbool)
        {
            //btnOpenPort.PerformClick();
            if (isbool)
            {
                setButtonBackColor(btnOpenPort);
            }
            else
            {
                OpenCloesPort();
            }

        }

        private void simpleButton4_Click_1(object sender, EventArgs e)
        {
            if (!sPortTemp.IsOpen && !IsUsbOpen && !m_open)//串口检测
            {
                DevExpress.XtraEditors.XtraMessageBox.Show("串口未打开");
                return;
            }
            //XChip_GroupWrite configFile = new XChip_GroupWrite(sPortTemp);
            //configFile.StartPosition = FormStartPosition.CenterParent;
            //configFile.ShowDialog();


            XChip_GroupWrite xchip_groupWrite = XChip_GroupWrite.GetInstance(sPortTemp);
            xchip_groupWrite.StartPosition = FormStartPosition.CenterScreen;
            xchip_groupWrite.Show();
            xchip_groupWrite.Focus();

        }
        /// <summary>
        /// 导出bin
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private async void simpleButton2_Click(object sender, EventArgs e)
        {
            //var binlistTempusb = BinHelp.BinList;

            //if (null == binlistTempusb || binlistTempusb.Count == 0)
            //{
            //    DevExpress.XtraEditors.XtraMessageBox.Show("无数据，请先下载！");
            //    return;
            //}
            //SaveFileDialog sfd = new SaveFileDialog();
            ////设置文件类型 
            //sfd.Filter = "BIN文件（*.bin）|*.bin";
            ////设置默认文件类型显示顺序 
            //sfd.FilterIndex = 1;
            ////保存对话框是否记忆上次打开的目录 
            //sfd.RestoreDirectory = true;
            ////设置文件名
            //sfd.FileName = "Xchip_Output_" + DateTime.Now.ToString("yyyyMMddHHmms");
            //var Save_BIN_Output_File_FileName_Path = string.Empty;

            //if (sfd.ShowDialog() == DialogResult.OK)
            //{
            //    Save_BIN_Output_File_FileName_Path = sfd.FileName.ToString();
            //}
            //BinHelp.BinOutFile(Save_BIN_Output_File_FileName_Path, binlistTempusb);
            //DevExpress.XtraEditors.XtraMessageBox.Show("导出完成");
            //return;
            if (!sPortTemp.IsOpen && !IsUsbOpen && !m_open)
            {
                DevExpress.XtraEditors.XtraMessageBox.Show("可用端口未打开");
                return;
            }
            //在点击“保存”时强制刷新下出图尺寸
            simpleButton17_Click(null, null);
            DialogResult dr = DevExpress.XtraEditors.XtraMessageBox.Show($"调整后的参数将保存到Flash中，请确认！", "提示", MessageBoxButtons.YesNo, MessageBoxIcon.Asterisk);
            if (dr == DialogResult.No)
            {
                return;
            }
            if (!sPortTemp.IsOpen)
            {
                var binlistTempusb = BinHelp.BinList;

                if (null == binlistTempusb || binlistTempusb.Count == 0)
                {
                    DevExpress.XtraEditors.XtraMessageBox.Show("无数据，请先下载！");
                    return;
                }

                var Save_BIN_Output_File_FileName_Path = string.Format("{0}\\Lib\\xc151_Bin\\GetUpdateUsbIndex.bin", Application.StartupPath);

                BinHelp.BinOutFile(Save_BIN_Output_File_FileName_Path, binlistTempusb);
                try
                {
                    if (IntPtr.Size == 8)
                    {
                        //var isbool = XChipUSB.UsbFlashWriteFile64(Save_BIN_Output_File_FileName_Path, 0x0);
                        bool success = await XChipUSB.WriteFileAsync(Save_BIN_Output_File_FileName_Path, 0);
                        if (success)
                        {
                            MessageBox.Show("文件写入成功！");
                        }
                        else
                        {
                            MessageBox.Show("文件写入失败！");
                            return;
                        }
                    }
                    else
                    {
                        bool success = await XChipUSB.WriteFileAsync(Save_BIN_Output_File_FileName_Path, 0);
                        if (success)
                        {
                            MessageBox.Show("文件写入成功！");
                        }
                        else
                        {
                            MessageBox.Show("文件写入失败！");
                            return;
                        }
                        //var isbool = XChipUSB.UsbFlashWriteFile86(Save_BIN_Output_File_FileName_Path, 0x0);
                        //this.Invoke(new Action(() =>
                        //{
                        //    while (isbool)
                        //    {
                        //        XChipUSB.CallBackInfo info = XChipUSB.GetProgressInfo86();
                        //        if (info.result < 0)
                        //        {

                        //            DevExpress.XtraEditors.XtraMessageBox.Show("烧入异常");
                        //            return;
                        //        }
                        //        else if (info.progress == 100 && info.result >= 0)
                        //        {
                        //            DevExpress.XtraEditors.XtraMessageBox.Show("烧入完成");
                        //            SerialSend.WriteRegister(0x80500137, 0xce, sPortTemp);
                        //            return;
                        //        }
                        //    }
                        //}));
                    }
                }
                catch (Exception ex)
                {

                    throw;
                }
                
                return;



            }
           
            BinHelp.IsPartition = Partition_check.Checked;
            //根据 分段发送测试
            var binlistTemp = BinHelp.GetUpdateIndex();
            if (null == binlistTemp || binlistTemp.Count == 0)
            {
                DevExpress.XtraEditors.XtraMessageBox.Show("无数据，请先下载！");
                return;
            }
            BinHelp.BinOutFile(string.Format("{0}\\Lib\\xc151_Bin\\GetUpdateIndex.bin", Application.StartupPath), binlistTemp);
            if (BinHelp.IsPartition)
            {
                var min = BinHelp.UpdateIndex.Min();
                //根据最小值找到头文件
                var minL = ((int)(min / 4000)) * 0x1000;
                //var temp = SerialSend.WriteRegister(BinHelp.BootSettingIdx, sPortTemp);
                var t1 = Convert.ToUInt32(minL) & 0xff;
                var t2 = Convert.ToUInt32(minL) >> 8 & 0xff;
                var t3 = Convert.ToUInt32(minL) >> 16 & 0xff;
                var t4 = Convert.ToUInt32(minL) >> 24 & 0xff;


                SerialSend.WriteRegister(BinHelp.FlashIdx, t1, sPortTemp);
                SerialSend.WriteRegister(BinHelp.FlashIdx + 1, t2, sPortTemp);
                SerialSend.WriteRegister(BinHelp.FlashIdx + 2, t3, sPortTemp);
                SerialSend.WriteRegister(BinHelp.FlashIdx + 3, t4, sPortTemp);

                var index = ParaList.Rx_flash_1k.FindIndex(c => c.PKey == "0xfffd" && c.PValue == "0x80");
                if (ParaList.Rx_flash_1k.Exists(c => c.PKey == $"0x{BinHelp.FlashIdx.ToString("X4").Replace("2000", "")}"))
                {
                    ParaList.Rx_flash_1k.Remove(ParaList.Rx_flash_1k.Find(c => c.PKey == $"0x{BinHelp.FlashIdx.ToString("X4").Replace("2000", "")}"));
                    ParaList.Rx_flash_1k.Remove(ParaList.Rx_flash_1k.Find(c => c.PKey == $"0x{(BinHelp.FlashIdx + 1).ToString("X4").Replace("2000", "")}"));
                    ParaList.Rx_flash_1k.Remove(ParaList.Rx_flash_1k.Find(c => c.PKey == $"0x{(BinHelp.FlashIdx + 2).ToString("X4").Replace("2000", "")}"));
                    ParaList.Rx_flash_1k.Remove(ParaList.Rx_flash_1k.Find(c => c.PKey == $"0x{(BinHelp.FlashIdx + 3).ToString("X4").Replace("2000", "")}"));
                }
                index = ParaList.Rx_flash_1k.FindIndex(c => c.PKey == "0xfffd" && c.PValue == "0x80");
                ParaList.Rx_flash_1k.Insert(index, new XModem.library.ParaModel() { PKey = $"0x{(BinHelp.FlashIdx + 3).ToString("X4").Replace("2000", "")}", PValue = $"0x{t4.ToString("X2")}" });
                ParaList.Rx_flash_1k.Insert(index, new XModem.library.ParaModel() { PKey = $"0x{(BinHelp.FlashIdx + 2).ToString("X4").Replace("2000", "")}", PValue = $"0x{t3.ToString("X2")}" });
                ParaList.Rx_flash_1k.Insert(index, new XModem.library.ParaModel() { PKey = $"0x{(BinHelp.FlashIdx + 1).ToString("X4").Replace("2000", "")}", PValue = $"0x{t2.ToString("X2")}" });
                ParaList.Rx_flash_1k.Insert(index, new XModem.library.ParaModel() { PKey = $"0x{BinHelp.FlashIdx.ToString("X4").Replace("2000", "")}", PValue = $"0x{t1.ToString("X2")}" });






                //SerialSend.WriteRegister(BinHelp.Xmodem_RX_Data_Dest_Type, 0x6, sPortTemp);
                //ParaList.Rx_flash_1k.Add(new XModem.library.ParaModel() { PKey = "0xfff0", PValue= "0x36" });
                //ParaList.Rx_flash_1k.Add(new XModem.library.ParaModel() { PKey = "0xfffd", PValue = "0x20" });
                //ParaList.Rx_flash_1k.Add(new XModem.library.ParaModel() { PKey = "0xfffe", PValue = "0x00" });
                //ParaList.Rx_flash_1k.Add(new XModem.library.ParaModel() { PKey = $"0x{BinHelp.FlashIdx.ToString("X4").Replace("2000","")}", PValue = $"0x{t1.ToString("X2")}" });
                //ParaList.Rx_flash_1k.Add(new XModem.library.ParaModel() { PKey = $"0x{(BinHelp.FlashIdx + 1).ToString("X4").Replace("2000", "")}", PValue = $"0x{t2.ToString("X2")}" });
                //ParaList.Rx_flash_1k.Add(new XModem.library.ParaModel() { PKey = $"0x{(BinHelp.FlashIdx + 2).ToString("X4").Replace("2000", "")}", PValue = $"0x{t3.ToString("X2")}" });
                //ParaList.Rx_flash_1k.Add(new XModem.library.ParaModel() { PKey = $"0x{(BinHelp.FlashIdx + 3).ToString("X4").Replace("2000", "")}", PValue = $"0x{t4.ToString("X2")}" });

            }
            ///重新计算sysclk  不使用输入方式 采用自动计算方式
            List<string> listsys = new List<string>();
            foreach (var item in RegisterSystemHelp.SysList)
            {
                listsys.Add(SerialSend.ReadRegister(Convert.ToUInt32(item, 16), sPortTemp).ToString("X2"));
            }
            double sys_clk = RegisterSystemHelp.sys_clk(listsys[0], listsys[1], listsys[2], listsys[3], listsys[4], listsys[5]);

            //double sys_clk = double.Parse(sys_clk_txt.Text);

            var fsysPath = string.Format("{0}\\Lib\\xc151_Bin\\FSys.txt", Application.StartupPath);
            var list = SYSHelper.GetFSys(sys_clk, 8);
            var list2 = SYSHelper.GetFsys_Bps(115200, sys_clk, 4);
            //写入静态list集合中
            SYSHelper.SetFsysBps(list);
            SYSHelper.SetFsysSystem(list2);
            //获取生成字符串
            var str = SYSHelper.CreateFsys();
            //写入文件
            File.WriteAllText(fsysPath, str);
            var path = string.Format("{0}\\Lib\\xc151_Bin\\Xchip_Output_{1}.bin", Application.StartupPath, DateTime.Now.ToString("yyyyMMddHHmms"));

            BinHelp.BinOutFile(path, binlistTemp);
            XmodemData.XmodemDataList(path, true);
            var binlength = SYSHelper.BinReader(path);
            var listbin = SYSHelper.GetUintToList(binlength, 8);
            SYSHelper.SetRxFlashLength(listbin, ParaList.Rx_flash_1k);
            SYSHelper.SetRxFlashEeprom(ParaList.Rx_flash_1k, false, false);
            if (BinHelp.IsPartition)
            {
                ParaList.Rx_flash_1k.ForEach(c =>
                {
                    if (c.PKey == "0x1329")
                    {
                        c.PValue = "0x06";
                    }
                });
            }

            var rxPath = string.Format("{0}\\Lib\\xc151_Bin\\RxFlash1K.txt", Application.StartupPath);
            var tStr = SYSHelper.CreateRxFlash1K();
            if (File.Exists(rxPath))
            {
                File.Delete(rxPath);
            }
            //写入文件
            File.WriteAllText(rxPath, tStr);

            RegisterFileWrite(fsysPath);//先发系统频率
            setShowMsg("发系统频率配置文件写入完成！");
            logger.Debug("发系统频率配置文件写入完成！");
            RegisterFileWrite(rxPath);//再发波特率
            setShowMsg("发波特率配置文件写入完成！");
            logger.Debug("发波特率配置文件写入完成！");
            SetSelectedPortConfig(sPortTemp.PortName, true);
            if (sPortTemp.IsOpen)
            {
                sPortTemp.Close();
                setButtonBackColor(btnOpenPort);
            }
            string msg = string.Empty;
            serialPort1.OpenCom(out msg);
        }


        List<XmodemRequest> rxtemplists = new List<XmodemRequest>();
        private FlashBase fb;

        //定义SerialPortHelper类
        private SerialPortHelper serialPort1;
        private SerialPortHelper serialPort2;

        //爆序号
        private int PackageTemp = 0;
        //判断是c 还是nak
        private int useCRC = -1;
        private bool isFinish = false;
        public string SavePath;
        /// <summary>
        /// 导入bin
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void simpleButton3_Click(object sender, EventArgs e)
        {


            if ((GetConfigValue("IsSerial") == "USB" && IsUsbOpen) || GetConfigValue("IsI2C") == "1")
            {
                uint temp0 = (uint)SerialSend.ReadRegister(BinHelp.BinToLength, sPortTemp, true);
                uint temp1 = (uint)SerialSend.ReadRegister(BinHelp.BinToLength + 1, sPortTemp, true);
                uint temp2 = (uint)SerialSend.ReadRegister(BinHelp.BinToLength + 2, sPortTemp, true);
                uint temp3 = (uint)SerialSend.ReadRegister(BinHelp.BinToLength + 3, sPortTemp, true);

                SavePath = string.Format("{0}\\Lib\\xc151_Bin\\Xchip_Output_{1}.bin", Application.StartupPath, DateTime.Now.ToString("yyyyMMddHHmms"));

                var binLength = Convert.ToUInt32($"{temp3.ToString("X2")}{temp2.ToString("X2")}{temp1.ToString("X2")}{temp0.ToString("X2")}", 16);
                if (IntPtr.Size == 8)
                {
                    XChipUSB.UsbFlashQuickReadFile64(SavePath, 0x0, binLength);
                }
                else
                {
                    XChipUSB.UsbFlashQuickReadFile86(SavePath, 0x0, binLength);
                }
                Thread.Sleep(1000);
                OpenBinParsing();
                Thread.Sleep(100);
                if (BinHelp.BinList.Count(c => !string.IsNullOrEmpty(c.note) && c.note.Contains("setting区1_31_") && !c.note.Contains("_en") && !c.module.Contains("Header")) <= 0)
                {
                    DevExpress.XtraEditors.XtraMessageBox.Show("不存在可以解析的配置文件！");
                    return;
                }
                if (BinHelp.usbList.Count <= 0)
                {
                    DevExpress.XtraEditors.XtraMessageBox.Show("无法解析Bin文件！请联系管理员！");
                    return;
                }
                DevExpress.XtraEditors.XtraMessageBox.Show("开启成功");
            }
            if (GetConfigValue("IsSerial") == "TVE")
            {
                //logger.Debug("开始Bin文件导出！");
                if (!sPortTemp.IsOpen)
                {
                    DevExpress.XtraEditors.XtraMessageBox.Show("可用端口未打开");
                    return;
                }
                SavePath = string.Format("{0}\\Lib\\xc151_Bin\\Xchip_Output_{1}.bin", Application.StartupPath, DateTime.Now.ToString("yyyyMMddHHmms"));
                uint temp0 = (uint)SerialSend.ReadRegister(BinHelp.BinToLength, sPortTemp);
                uint temp1 = (uint)SerialSend.ReadRegister(BinHelp.BinToLength + 1, sPortTemp);
                uint temp2 = (uint)SerialSend.ReadRegister(BinHelp.BinToLength + 2, sPortTemp);
                uint temp3 = (uint)SerialSend.ReadRegister(BinHelp.BinToLength + 3, sPortTemp);

                var binLength = Convert.ToInt32($"{temp3.ToString("X2")}{temp2.ToString("X2")}{temp1.ToString("X2")}{temp0.ToString("X2")}", 16);

                var receiveTempCout = Math.Ceiling(binLength / 1024.0);

                rxtemplists = new List<XmodemRequest>();
                /*
                 //计算长度
                //计算系统频率
                当前写死 为了测试 后期可能是活动
                */
                double sys_clk = double.Parse(sys_clk_txt.Text);
                //当前已经修改成获取选项
                var list1 = new List<string>();
                foreach (var item in RegisterSystemHelp.ArmList)
                {
                    list1.Add(SerialSend.ReadRegister(Convert.ToUInt32(item, 16), sPortTemp).ToString("X2"));
                }
                var dou2 = RegisterSystemHelp.arm_clk(list1[0], list1[1], list1[2], list1[3], list1[4], list1[5]);

                if (sys_clk != dou2)
                {
                    sys_clk = dou2;
                }
                var fsysPath = string.Format("{0}\\Lib\\xc151_Bin\\FSys.txt", Application.StartupPath);
                var list = SYSHelper.GetFSys(sys_clk, 8);
                var list2 = SYSHelper.GetFsys_Bps(115200, sys_clk, 4);
                //写入静态list集合中
                SYSHelper.SetFsysBps(list);
                SYSHelper.SetFsysSystem(list2);
                //获取生成字符串
                var str = SYSHelper.CreateFsys();
                //写入文件
                File.WriteAllText(fsysPath, str);
                if (binLength == 0x0)
                {
                    setShowMsg("监测->获取Bin长度地址为0");
                    logger.Debug("监测->获取Bin长度地址为0");
                    return;
                }

                var listbin = SYSHelper.GetUintToList(binLength, 8);
                //更新长度 // 修改成接收
                SYSHelper.SetTxFlashLength(listbin, ParaList.Tx_flash_1k);
                SYSHelper.SetTxFlashEeprom(ParaList.Tx_flash_1k, false, false);
                //SYSHelper.SetTxFlashLength(listbin, ParaList.Tx_flash_1k);
                //SYSHelper.SetTxFlashEeprom(ParaList.Tx_flash_1k, false, eepromcheck.Checked);

                var txPath = string.Format("{0}\\Lib\\xc151_Bin\\TxFlash1K.txt", Application.StartupPath);
                var tStr = SYSHelper.CreateTxFlash1K();
                File.WriteAllText(txPath, tStr);


                //获取系统评率
                RegisterFileWrite(fsysPath);//先发系统频率
                setShowMsg("发系统频率配置文件写入完成！");
                logger.Debug("发系统频率配置文件写入完成!");
                RegisterFileWrite(txPath);//再发波特率
                SetSelectedPortConfig(sPortTemp.PortName, false);
                setShowMsg("发波特率配置文件写入完成！");
                logger.Debug("发波特率配置文件写入完成！");
                if (sPortTemp.IsOpen)
                {
                    sPortTemp.Close();

                    setButtonBackColor(btnOpenPort);
                }
                string msg = string.Empty;
                serialPort2.OpenCom(out msg);
                serialPort2.Write(new byte[] { 0x15 });
                setShowMsg(msg);
                DevExpress.XtraEditors.XtraMessageBox.Show("开启成功");
            }

            //解析导出Bin文件


            //OpenFileDialog sfd = new OpenFileDialog();
            ////设置文件类型 
            //sfd.Filter = "导入BIN（*.bin）|*.bin";
            ////设置默认文件类型显示顺序 
            //sfd.FilterIndex = 1;
            ////保存对话框是否记忆上次打开的目录 
            //sfd.RestoreDirectory = true;
            //if (sfd.ShowDialog() != DialogResult.OK) return;
            //string foldPath = Path.GetDirectoryName(sfd.FileName);
            //AppHelper.UpdateAppConfig("Folder_Road_Force", foldPath);
            //List<BinBase> blist;
            /////读取文件全部内容
            //blist = BinHelp.BinToList(sfd.FileName);
            //int headKey = 0x368;
            ////headLength是包含crc校验的长度，xclist是不包含crc校验
            //int headLength = 0x320;
            ////获取存放的开始地址 计算结束地址  赋值类
            //var HeadStartAddr = Convert.ToUInt32("0x" + blist[headKey + 1].original.ToString("X2") + blist[headKey].original.ToString("X2"), 16);
            //var HeadEndAddr = HeadStartAddr + headLength;

            //xc151binparsingManager xcm = new xc151binparsingManager();
            //var xclist = xcm.GetList();
            //blist = BinHelp.BinBaseToNode(blist, xclist);

        }

        private void OpenBinParsing()
        {
            Thread.Sleep(1500);
            if (!string.IsNullOrEmpty(SavePath))
            {
                logger.Debug("开始文件解析");
                //xc151binparsingManager xcm = new xc151binparsingManager();
                //var xclist = xcm.GetList();
                xc151_exManager xcmex = new xc151_exManager();
                var xclist = JsonConvert.DeserializeObject<List<xc151binparsing>>(xcmex.GetListToXc151Binparsing()).OrderBy(c => c.Id).ToList();
                BinHelp.OpenBinFile(SavePath, xclist, IsUsbOpen);
                logger.Debug("结束文件解析");
            }
        }


        /// <summary>
        /// 寄存器文件写
        /// </summary>
        /// <param name="path"></param>
        private void RegisterFileWrite(string path)
        {
            long test_value1 = (long)BaseRegisterMap.SPI_BASE_ADDR;
            uint test_value2 = (uint)SPIRegisterMap.SPI_FUNCTION_SELECT;
            uint FUNCT_SEL_ADDR = (uint)(test_value1 + test_value2);
            fb = new FlashBase(sPortTemp);
            //fb.SendEvent += Fb_SendEvent;
            try
            {
                string txt_str = String.Empty;
                string[] ss;
                UInt32 reg_address;
                UInt32 reg_data;
                UInt32 Value;
                StreamReader f2 = new StreamReader(path, System.Text.Encoding.GetEncoding("gb2312"));//gb2312编码，为制定文件名初始化

                while (f2.Peek() > -1)
                {
                    txt_str = f2.ReadLine().Trim();
                    ss = txt_str.Split(',');
                    if (ss.Length >= 2)
                    {

                        if (ss[0].Trim() == "0xfffd")
                        {

                            addr = (Convert.ToUInt32(ss[1].Trim(), 16) & 0xff) << 24;
                        }
                        else if (ss[0].Trim() == "0xfffe")
                        {

                            //addr = 0x80000000;
                            addr += (Convert.ToUInt32(ss[1].Trim(), 16) & 0xff) << 16;
                        }
                        else if (ss[0].Trim() == "0xffff")
                        {

                            uint t;
                            t = (Convert.ToUInt32(ss[1].Trim(), 16) & 0xff);
                            Thread.Sleep(1000);
                        }
                        else if (ss[0].Trim() == "0xfff3")
                        {

                            UInt16 chip_id;
                            reg_address = 0x80500010;
                            reg_data = 0;
                            fb.ReadRegDataARM(0x11, reg_address, ref reg_data, sPortTemp);
                            chip_id = (UInt16)(reg_data >> 16);
                            if (chip_id != Convert.ToUInt32(ss[1].Trim(), 16))
                            {
                                f2.Close();//释放系统资源
                                f2.Dispose();
                                setShowMsg("Chip ID don't match, Write stopped!");
                                break;
                            }

                        }
                        else
                        {

                            reg_address = addr + (Convert.ToUInt32(ss[0].Trim(), 16) & 0xffff);
                            reg_data = Convert.ToUInt32(ss[1].Trim(), 16);
                            int byte_sel = (int)(reg_address) & 0x3;
                            byte_sel = byte_sel * 8;

                            //int reg_data = Convert.ToUInt32(txtBoxRegData.Text, 16);
                            reg_data = reg_data & 0xff;
                            reg_data = reg_data << byte_sel;
                            Value = fb.SendRegDataARM(0x21, reg_address, reg_data, sPortTemp);

                            if (Value != 0x21)
                            {
                                f2.Close();//释放系统资源
                                f2.Dispose();
                                //setShowMsg("error ->!= 0x21");
                                break;
                            }
                        }
                    }

                }

                Application.DoEvents();
                f2.Close();//释放系统资源
                f2.Dispose();

            }
            catch (Exception ex)
            {
                //setShowMsg(msg);
                setShowMsg(ex.Message.ToString());
            }

        }


        private void barButtonItem21_ItemClick(object sender, DevExpress.XtraBars.ItemClickEventArgs e)
        {
            this.splashScreenManager1.ShowWaitForm();
            NavigationPage page = new NavigationPage();
            if (null != xChip_ToBin_Security)
            {
                xChip_ToBin_Security.isSecurity = false;
            }
            xChip_ToBin_Security = XChip_ToBin_Security.Instance(Bincurrency_BLL, Serialdata_BLL, sPortTemp, false);

            xChip_ToBin_Security.Dock = DockStyle.Fill;
            page.Controls.Add(xChip_ToBin_Security);
            page.Name = "page_ToBin_Security";
            navigationFrame.Pages.Add(page);
            navigationFrame.SelectedPage = page;
            this.splashScreenManager1.CloseWaitForm();


            //if (navigationFrame.Pages.Any(c => c.Caption == "page_ToBin_Security"))
            //{
            //    navigationFrame.SelectedPageIndex = navigationFrame.Pages.FindIndex(c => c.Caption == "page_ToBin_Security");

            //}
            //else
            //{

            //    this.splashScreenManager1.ShowWaitForm();
            //    NavigationPage page = new NavigationPage();

            //    xChip_ToBin_Security = new XChip_ToBin_Security(Bincurrency_BLL, Serialdata_BLL, true);
            //    xChip_ToBin_Security.Dock = DockStyle.Fill;
            //    page.Controls.Add(xChip_ToBin_Security);
            //    page.Name = "page_ToBin_Security";
            //    navigationFrame.Pages.Add(page);
            //    navigationFrame.SelectedPage = page;
            //    this.splashScreenManager1.CloseWaitForm();
            //}

        }
        /// <summary>
        /// 刷新监测
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void simpleButton5_Click(object sender, EventArgs e)
        {

            if (GetConfigValue("IsSerial") == "USB" || GetConfigValue("IsI2C") == "1")
            {
                uint pVule = 0x0;
                uint pfps = 0x0;
                var isbool = false;
                if (GetConfigValue("IsI2C") == "1")
                {
                    pVule = (uint)SerialSend.ReadRegister(BinHelp.CurrentSize, sPortTemp);
                    pfps = (uint)SerialSend.ReadRegister(0x200065cc, sPortTemp);
                }
                else
                {
                    if (IntPtr.Size == 8)
                    {
                        isbool = XChipUSB.UsbRegisterRead64(BinHelp.CurrentSize, ref pVule, true);
                        isbool = XChipUSB.UsbRegisterRead64(0x200065cc, ref pfps, true);
                        SerialSend.Sendser("R:0x" + (BinHelp.CurrentSize).ToString("X2"), pVule.ToString("X2"));


                    }
                    else
                    {
                        isbool = XChipUSB.UsbRegisterRead86(BinHelp.CurrentSize, ref pVule, true);
                        isbool = XChipUSB.UsbRegisterRead86(0x200065cc, ref pfps, true);
                        SerialSend.Sendser("R:0x" + (BinHelp.CurrentSize).ToString("X2"), pVule.ToString("X2"));
                    }
                }
                
                //200065cc显示当前出图帧率
                var chang = (int)(pVule >> 16); // 使用右移16位操作来获取高16位  
                var kuang = (int)(pVule & 0xFFFF); // 使用位与操作来获取低16位  
                int fps = 0;
                if (pfps != 0)
                {
                    fps = (int)(10000000 / pfps);
                }

                monitorLab.Text = $"出图尺寸:{chang} * {kuang} {fps}fps";
            }
            else
            {
                if (!sPortTemp.IsOpen)
                {
                    //DevExpress.XtraEditors.XtraMessageBox.Show("可用端口未打开");
                    return;
                }
                uint temp = (uint)SerialSend.ReadRegister(BinHelp.BootSettingIdx, sPortTemp);
                //var aaa = FlashRead((FlashRead(Convert.ToUInt32("368", 16)) + temp * 4 + 0xd4) + 0x0c);
                if (null != BinHelp.lspList)
                {
                    var lspModel = BinHelp.lspList.Find(c => c.SettingHex == temp);
                    monitorLab.Text = $"{lspModel.tName}-{lspModel.vName}";
                }
            }

        }

        private uint FlashRead(uint flash_address)
        {
            //Fb_SendEvent("Flash操作->读 开始执行\r\n");

            long test_value1 = (long)BaseRegisterMap.SPI_BASE_ADDR;

            uint test_value2 = (uint)SPIRegisterMap.SPI_FUNCTION_SELECT;
            uint FUNCT_SEL_ADDR = (uint)(test_value1 + test_value2);

            test_value2 = (uint)SPIRegisterMap.SPI_CONTROL;
            uint CONTROL_ADDR = (uint)(test_value1 + test_value2);

            test_value2 = (uint)SPIRegisterMap.SPI_SHIFT_CONTROL;
            uint SHIFT_ADDR = (uint)(test_value1 + test_value2);

            test_value2 = (uint)SPIRegisterMap.SPI_SHIFT_TXD0;
            uint TXD0_ADDR = (uint)(test_value1 + test_value2);

            test_value2 = (uint)SPIRegisterMap.SPI_SHIFT_TXD1;
            uint TXD1_ADDR = (uint)(test_value1 + test_value2);


            test_value2 = (uint)SPIRegisterMap.SPI_SHIFT_RXD0;
            uint RXD0_ADDR = (uint)(test_value1 + test_value2);

            test_value2 = (uint)SPIRegisterMap.SPI_SHIFT_RXD1;
            uint RXD1_ADDR = (uint)(test_value1 + test_value2);


            //uint flash_address = Convert.ToUInt32(txtBoxFlashAddress.Text, 16);

            uint spi_shift_cnt;
            uint spi_rxvld_cnt;
            uint senddata;
            uint recvdata = 0;
            uint op_code = 0x03;

            FlashBase fb = new FlashBase(sPortTemp);
            fb.SendRegDataARM(0x1, FUNCT_SEL_ADDR, 0x1, sPortTemp);
            //fb.SendEvent += Fb_SendEvent;
            Thread.Sleep(200);
            senddata = (((flash_address & 0xff) << 24) + ((flash_address & 0xff00) << 8) + ((flash_address & 0xff0000) >> 8) + op_code);
            fb.SendRegDataARM(0x1, TXD0_ADDR, senddata, sPortTemp);
            Thread.Sleep(200);
            spi_shift_cnt = 64;
            spi_rxvld_cnt = 32;
            senddata = (3 << 16) + (spi_rxvld_cnt << 8) + (spi_shift_cnt << 0);
            fb.SendRegDataARM(0x1, SHIFT_ADDR, senddata, sPortTemp);
            Thread.Sleep(200);

            fb.ReadRegDataARM(0x11, RXD0_ADDR, ref recvdata, sPortTemp);
            //Fb_SendEvent("Flash操作->读 执行完成\r\n");
            return recvdata;

        }
        /// <summary>
        /// 配置串口
        /// </summary>
        /// <param name="isStopBits">Parity 是空校验 true </param>
        /// <param name="issend"> true 使用发送  false 使用接收</param>
        /// <param name="useBlock1K"> true 表示是1kxmodel  false还是 xmodel</param>
        void SetSelectedPortConfig(string Ports, bool issend, bool isStopBits = true, bool _useBlock1K = true)
        {
            if (issend)
            {
                serialPort1.ConfigSerialPort = new ConfigComType()
                {
                    //PortName = comBoxPorts.Text,
                    PortName = Ports,
                    BaudRate = 115200,//xmodem波特率定死成115200,需要改3个地方setSelectedPortConfig、ConfigSerialPort、comBoxFSys_EditValueChanged
                    //BaudRate = int.Parse(comBoxBaudRate.Text),
                    //DataBits = int.Parse(comBoxDataBits.Text),
                    DataBits = 8,
                    StopBits = SerialPortHelperLib.StopBits.One,
                    //Parity = isStopBits ? SerialPortHelperLib.Parity.None : (SerialPortHelperLib.Parity)Enum.Parse(typeof(SerialPortHelperLib.Parity), comBoxParity.EditValue.ToString()),
                    Parity = isStopBits ? SerialPortHelperLib.Parity.None : SerialPortHelperLib.Parity.Even,

                };
                ////初始化全局变量
                PackageTemp = 0;
                ////useBlock1K = comBoxAgreement.EditValue.ToString() == "0" ? true : false;
                useCRC = -1;
                serialPort1.SerialReceviedTimeInterval = 5;
                serialPort1.SerialWriteTimeInterval = 0;
                //useBlock1K = _useBlock1K;
            }
            else
            {
                serialPort2.ConfigSerialPort = new ConfigComType()
                {
                    //PortName = comBoxPorts.Text,
                    PortName = Ports,
                    BaudRate = 115200,//xmodem波特率定死成115200,需要改3个地方setSelectedPortConfig、ConfigSerialPort、comBoxFSys_EditValueChanged
                                      //BaudRate = int.Parse(comBoxBaudRate.Text),
                                      //DataBits = int.Parse(comBoxDataBits.Text),
                    DataBits = 8,
                    StopBits = SerialPortHelperLib.StopBits.One,
                    //Parity = isStopBits ? SerialPortHelperLib.Parity.None : (SerialPortHelperLib.Parity)Enum.Parse(typeof(SerialPortHelperLib.Parity), comBoxParity.EditValue.ToString()),
                    Parity = isStopBits ? SerialPortHelperLib.Parity.None : SerialPortHelperLib.Parity.Even,
                };
                ////初始化全局变量
                PackageTemp = 0;
                ////useBlock1K = comBoxAgreement.EditValue.ToString() == "0" ? true : false;
                useCRC = -1;
                serialPort2.SerialReceviedTimeInterval = 30;
                serialPort2.SerialWriteTimeInterval = 1;
                //useBlock1K = _useBlock1K;
                //设置线程传送长度
                if (_useBlock1K)
                {
                    serialPort2.SerialReceviedLengthMax = 1028;
                }
                else
                {
                    serialPort2.SerialReceviedLengthMax = 132;
                }
            }
        }

        /// <summary>
        /// 记录上次一次发送序号
        /// </summary>
        private int tempReceived = 0;
        /// <summary>
        /// 记录当接收长度超过255重新开始计数
        /// </summary>
        private int tempSize = 0;
        private void SerialPortDataReceivedProcess2(object sender, byte[] arrDataReceived)
        {
            this.Invoke(new Action(() =>
            {

                try
                {
                    if (arrDataReceived.Length != 1028)
                    {
                        if (arrDataReceived.First() == 04)//表示结束接收
                        {
                            serialPort2.Write(new byte[] { 0x06, 0x06, 0x06, 0x06 }); //告诉终端结束这次发送
                            Thread.Sleep(1000);
                            receivePath();
                            serialPort2.SPort.DiscardInBuffer();
                            serialPort2.SPort.DiscardOutBuffer();
                            string msg = "导出完成！";
                            setShowMsg(msg);
                            logger.Debug(msg);
                            serialPort2.CloseCom(out msg);
                            setShowMsg(msg);
                            logger.Debug(msg);
                            isFinish = true;
                        }
                        else
                        {
                            string msg = "->获取数据长度不够，重新获取！";
                            setShowMsg(string.Format(msg));
                            logger.Debug(msg);
                            serialPort2.CloseCom(out msg);
                            tempSize = 0;
                        }
                        return;
                    }

                    if (arrDataReceived.First() == 04)//表示结束接收
                    {
                        serialPort2.Write(new byte[] { 0x06, 0x06, 0x06, 0x06 }); //告诉终端结束这次发送
                                                                                  //休眠下 导入到文件
                        Thread.Sleep(1000);
                        receivePath();

                        serialPort2.SPort.DiscardInBuffer();
                        serialPort2.SPort.DiscardOutBuffer();
                        string msg = "导出完成！";
                        setShowMsg(msg);
                        logger.Debug(msg);
                        serialPort2.CloseCom(out msg);
                        setShowMsg(msg);
                        logger.Debug(msg);
                        isFinish = true;
                        return;
                    }
                    //接收数据业务处理部分
                    else if (arrDataReceived.First() == (2)) //如果是1k 等于2 如果是k 就是1 处理头部分文件
                    {
                        List<byte> tembyte = new List<byte>();
                        XmodemRequest xRequest = new XmodemRequest();
                        xRequest.ControlCharacter = arrDataReceived.First();
                        xRequest.PackageNo = arrDataReceived[1];
                        var tempIndex = Convert.ToInt32(xRequest.PackageNo) - 1; //接收第二位
                        xRequest.PackageInverseNo = arrDataReceived[2];

                        byte lastCrc;
                        //判断校验位

                        xRequest.DataList = arrDataReceived.Skip(3).Take(1024).ToList();
                        tembyte.AddRange(arrDataReceived.Skip(3).Take(1024));
                        xRequest.CheckBit = new byte[] { arrDataReceived.Skip(1027).Take(1).First() };
                        lastCrc = arrDataReceived.Skip(1027).Take(1).First(); //获取校验位

                        if (lastCrc != BitConverter.GetBytes(XModem.library.Port.GetCkSum(tembyte.ToArray()))[0]) //判断校验位是否正确
                        {
                            setShowMsg(string.Format("校验位不正确重新发送NAK"));
                            logger.Debug("校验位不正确重新发送NAK");
                            serialPort2.Write(new byte[] { 0x15 }); //重新NAk获取

                        }
                        else
                        {
                            serialPort2.Write(new byte[] { 0x06 }); //获取下一个
                            if (tempIndex != tempReceived)
                            {
                                tempSize++;
                            }

                            xRequest.No = tempSize;
                            setShowMsg(string.Format("->导出数据{0}包", tempSize));

                            rxtemplists.Add(xRequest);
                            tempReceived = tempIndex;
                        }

                    }
                    else if (arrDataReceived.First() == 24)
                    {
                        simpleButton4.Text = "导出";
                        string msg = "连接超时！";
                        setShowMsg(msg);
                        logger.Debug(msg);
                        serialPort2.CloseCom(out msg);
                        setShowMsg(msg);
                        logger.Debug(msg);
                    }
                    else
                    {
                        serialPort2.Write(new byte[] { 0x15 }); //重新NAk获取
                    }

                }
                catch (Exception ex)
                {
                    serialPort2.DiscardInBuffer();
                    string msg = "导出错误信息:";
                    setShowMsg(msg);
                    logger.Debug(msg);
                    serialPort2.CloseCom(out msg);
                    logger.Debug(msg);
                    setShowMsg(string.Format("导出错误信息：{0}", ex.Message.ToString()));
                    logger.Debug(string.Format("导出错误信息：{0}", ex.Message.ToString()));
                    tempSize = 0;
                }


            }));
        }


        /// <summary>
        /// 导出路径
        /// </summary>
        /// <param name="path"></param>
        private void receivePath()
        {
            //保存数据到路劲下
            //去除重复数据据
            rxtemplists = rxtemplists.Distinct(new XModemForm.ListByteComparer()).ToList();

            using (FileStream fs = new FileStream(SavePath, FileMode.Create))
            {
                using (BinaryWriter plik = new BinaryWriter(fs))
                {
                    //if (templists.Count>= receiveTempCout)
                    //{

                    var lastrx = rxtemplists.Last();
                    if (lastrx.DataList[0] == 0x1a && lastrx.DataList[1] == 0x0 && lastrx.DataList.Last() == 0x0)
                    {
                        rxtemplists.Remove(lastrx);
                    }

                    foreach (var item in rxtemplists)
                    {

                        foreach (var temD in item.DataList)
                        {

                            plik.Write(temD);
                        }
                    }

                }
            }
            tempSize = 0;
            Thread.Sleep(100);
            OpenBinParsing();
        }
        private void SerialPortDataReceivedProcess1(object sender, byte[] arrDataReceived)
        {
            this.Invoke(new Action(() =>
            {
                try
                {
                    setShowMsg(string.Format("->接收:{1}  烧入{0}次数。。。", PackageTemp, Convert.ToString(arrDataReceived[0], 16)));
                    //发送数据业务处理部分
                    switch (arrDataReceived[0])
                    {

                        case 0x43: //表示c
                            {
                                useCRC = 0;

                                serialPort1.WriteByte(XmodemData.xmodem1k_C[PackageTemp].ToArray());

                            }
                            break;
                        case 0x15: //表示nak
                            {
                                useCRC = 1;
                                if (PackageTemp > 0)
                                {
                                    serialPort1.WriteByte(XmodemData.xmodem1k_N[PackageTemp - 1].ToArray());
                                }
                                else
                                {
                                    serialPort1.WriteByte(XmodemData.xmodem1k_N[PackageTemp].ToArray());
                                }



                            }
                            break;
                        case 0x06: //表示ack
                            {

                                //if (true)
                                //{
                                if (PackageTemp > XmodemData.xmodem1k_C.Count - 1)
                                {
                                    //////发送取消命令 EOT 0x04
                                    serialPort1.Write(new byte[] { 0x04, 0x04, 0x04, 0x04, 0x04, 0x04 });
                                    //////这里关闭通讯 切换回以前的串口通讯
                                    Thread.Sleep(1000); //由于在多线程中  如果需要关闭就需要添加延迟 然在关闭
                                    string msg = "烧写完成！";
                                    setShowMsg(msg);
                                    logger.Debug(msg);
                                    serialPort1.CloseCom(out msg);
                                    setShowMsg(msg);
                                    logger.Debug(msg);
                                    isFinish = true;
                                    serialPort1.DiscardInBuffer();
                                    DevExpress.XtraEditors.XtraMessageBox.Show("烧写完成", "提示", MessageBoxButtons.OK, MessageBoxIcon.Asterisk);
                                    ////打开串口
                                    //if (null != OpenPortButtonClick)
                                    //{
                                    //    OpenPortButtonClick();
                                    //}
                                    return;
                                }



                                if (useCRC == 0)
                                {
                                    serialPort1.WriteByte(XmodemData.xmodem1k_C[PackageTemp].ToArray());
                                }
                                if (useCRC == 1)
                                {
                                    serialPort1.WriteByte(XmodemData.xmodem1k_N[PackageTemp].ToArray());
                                }
                                PackageTemp++;
                            }
                            break;
                        case 0x18:
                            {
                                serialPort1.Write(new byte[] { 0x04, 0x04, 0x04, 0x04, 0x04, 0x04 });
                                string msg = "烧写失败";
                                setShowMsg(msg);
                                logger.Debug(msg);
                                serialPort1.CloseCom(out msg);
                                setShowMsg(msg);
                                logger.Debug(msg);
                                serialPort1.DiscardInBuffer();
                            }
                            break;
                        default:
                            {
                                string msg = $"接收到错误指令{arrDataReceived[0]},无法继续，烧写失败";
                                setShowMsg(msg);
                                logger.Debug(msg);
                                serialPort1.CloseCom(out msg);
                                setShowMsg(msg);
                                logger.Debug(msg);
                                serialPort1.DiscardInBuffer();
                            }
                            break;
                    }

                }
                catch (Exception ex)
                {
                    string msg = "烧写失败";
                    serialPort1.DiscardInBuffer();
                    setShowMsg(msg);
                    logger.Debug(msg);
                    serialPort1.CloseCom(out msg);
                    setShowMsg(string.Format("烧写错误信息：{0}", ex.Message.ToString()));
                    logger.Debug(string.Format("烧写错误信息：{0}", ex.Message.ToString()));
                }
            }));
        }

        private void SerialPortErrorProcess(object sender, enumSerialError enumError, string strError)
        {
            this.Invoke(new Action(() =>
            {
                switch (enumError)
                {
                    case enumSerialError.LinkError:
                        string str = string.Empty;
                        if (!isFinish)
                        {
                            if (serialPort1.IsOpen)
                            {
                                serialPort1.CloseCom(out str);
                            }

                            if (serialPort2.IsOpen)
                            {
                                serialPort2.CloseCom(out str);
                            }


                        }
                        break;
                    case enumSerialError.WriteError:
                        //Fb_SendEvent(string.Format("发送错误：{0}", strError));
                        break;
                    case enumSerialError.ReceivedError:
                        //Fb_SendEvent(string.Format("接收错误：{0}", strError));
                        break;
                    default:
                        break;
                }
            }));
        }

        private void barButtonItem40_ItemClick(object sender, DevExpress.XtraBars.ItemClickEventArgs e)
        {

            //xc151binparsingManager bll = new xc151binparsingManager();
            //var list = bll.GetList();
            // xc151Manager bll2 = new xc151Manager();
            // var list2 = bll2.GetList();
            // bindefaultManager bll3 = new bindefaultManager();
            // var list3 = bll3.GetList();

            //var str = Newtonsoft.Json.JsonConvert.SerializeObject(list);
            // var str2 = Newtonsoft.Json.JsonConvert.SerializeObject(list2);
            // var str3 = Newtonsoft.Json.JsonConvert.SerializeObject(list3);
            //xc151_exManager bll1 = new xc151_exManager();
            //bll1.Insert(new xc151_ex()
            //{
            //    Data = AESExample.EncryptString(str),
            //    Type = "xc151usbgraphics"
            //});
            // bll1.Insert(new xc151_ex()
            // {
            //     Data = AESExample.EncryptString(str2),
            //     Type = "xc151"
            // });
            // bll1.Insert(new xc151_ex()
            // {
            //     Data = AESExample.EncryptString(str3),
            //     Type = "bindefault"
            // });

            //var list4 = bll1.GetList();

            //foreach (var item in list4)
            //{
            //    switch (item.Type)
            //    {
            //        case "xc151binparsing":
            //            var str6 = AESExample.DecryptString(item.Data);
            //            break;
            //        case "xc151":
            //            var str7 = AESExample.DecryptString(item.Data);
            //            break;
            //        case "bindefault":
            //            var str8 = AESExample.DecryptString(item.Data);
            //            break;
            //        case "xc151usbgraphics":
            //            var str9 = AESExample.DecryptString(item.Data);
            //            if (str9 == str) {

            //            }
            //            break;
            //        default:
            //            break;
            //    }
            //}
            XChip_CToCode xchic = new XChip_CToCode();
            xchic.StartPosition = FormStartPosition.CenterScreen;
            xchic.ShowDialog();

        }

        private void USBSwitch()
        {
            if (null != xChip_AE) xChip_AE.IsUsbOpen = IsUsbOpen;
            if (null != xChip_AWB) xChip_AWB.IsUsbOpen = IsUsbOpen;
            if (null != xChip_CMX) xChip_CMX.IsUsbOpen = IsUsbOpen;
            if (null != xChip_DNS) xChip_DNS.IsUsbOpen = IsUsbOpen;
            //if (null != xChip_DETAIL) xChip_DETAIL.sPortTemp = sPortTemp;
            if (null != xChip_GAMMA) xChip_GAMMA.IsUsbOpen = IsUsbOpen;
            if (null != xChip_SDE) xChip_SDE.IsUsbOpen = IsUsbOpen;
            if (null != xChip_LENC) xChip_LENC.IsUsbOpen = IsUsbOpen;
            if (null != xChip_Scene_Switch) xChip_Scene_Switch.IsUsbOpen = IsUsbOpen;
            if (null != xChip_CRL) xChip_CRL.IsUsbOpen = IsUsbOpen;
            if (null != xChip_CADJ) xChip_CADJ.IsUsbOpen = IsUsbOpen;
            if (null != xChip_DNR_CAL) xChip_DNR_CAL.IsUsbOpen = IsUsbOpen;
            //if (null != xChip_Gpio) xChip_Gpio.IsUsbOpen = IsUsbOpen;
            if (null != xChip_HDR) xChip_HDR.IsUsbOpen = IsUsbOpen;
            if (null != xChip_HDR_Ae) xChip_HDR_Ae.IsUsbOpen = IsUsbOpen;
            if (null != xChip_HDR_GAMMA) xChip_HDR_GAMMA.IsUsbOpen = IsUsbOpen;
            if (null != xChip_Reg_Yde) xChip_Reg_Yde.IsUsbOpen = IsUsbOpen;
            if (null != xChip_Reg_Ynr) xChip_Reg_Ynr.IsUsbOpen = IsUsbOpen;
            if (null != xChip_Reg_Cfa) xChip_Reg_Cfa.IsUsbOpen = IsUsbOpen;
            if (null != xChip_Reg_Snr) xChip_Reg_Snr.IsUsbOpen = IsUsbOpen;
            if (null != xChip_CADJ) xChip_CADJ.IsUsbOpen = IsUsbOpen;
            if (null != xChip_Gpio) xChip_Gpio.IsUsbOpen = IsUsbOpen;
            if (null != xChip_XModem) xChip_XModem.IsUsbOpen = IsUsbOpen;
            if (null != xChip_Flash) xChip_Flash.IsUsbOpen = IsUsbOpen;
            //if (null != xChip_Reg_FCC) xChip_Reg_FCC.IsUsbOpen = IsUsbOpen;
            if (null != xChip_TopReg) xChip_TopReg.IsUsbOpen = IsUsbOpen;
            if (null != xChip_HDR_Ae) xChip_HDR_Ae.IsUsbOpen = IsUsbOpen;
            SerialSend.IsUsbOpen = IsUsbOpen;

            if (null != xChip_AE) xChip_AE.m_open = m_open;
            if (null != xChip_AWB) xChip_AWB.m_open = m_open;
            if (null != xChip_CMX) xChip_CMX.m_open = m_open;
            if (null != xChip_DNS) xChip_DNS.m_open = m_open;
            //if (null != xChip_DETAIL) xChip_DETAIL.sPortTemp = sPortTemp;
            if (null != xChip_GAMMA) xChip_GAMMA.m_open = m_open;
            if (null != xChip_SDE) xChip_SDE.m_open = m_open;
            if (null != xChip_LENC) xChip_LENC.m_open = m_open;
            if (null != xChip_Scene_Switch) xChip_Scene_Switch.m_open = m_open;
            if (null != xChip_CRL) xChip_CRL.m_open = m_open;
            if (null != xChip_CADJ) xChip_CADJ.m_open = m_open;
            if (null != xChip_DNR_CAL) xChip_DNR_CAL.m_open = m_open;
            //if (null != xChip_Gpio) xChip_Gpio.IsUsbOpen = IsUsbOpen;
            if (null != xChip_HDR) xChip_HDR.m_open = m_open;
            if (null != xChip_HDR_Ae) xChip_HDR_Ae.m_open = m_open;
            if (null != xChip_HDR_GAMMA) xChip_HDR_GAMMA.m_open = m_open;
            if (null != xChip_Reg_Yde) xChip_Reg_Yde.m_open = m_open;
            if (null != xChip_Reg_Ynr) xChip_Reg_Ynr.m_open = m_open;
            if (null != xChip_Reg_Cfa) xChip_Reg_Cfa.m_open = m_open;
            if (null != xChip_Reg_Snr) xChip_Reg_Snr.m_open = m_open;
            if (null != xChip_CADJ) xChip_CADJ.m_open = m_open;
            if (null != xChip_Gpio) xChip_Gpio.m_open = m_open;
            //if (null != xChip_XModem) xChip_XModem.m_open = m_open;
            //if (null != xChip_Flash) xChip_Flash.m_open = m_open;
            //if (null != xChip_Reg_FCC) xChip_Reg_FCC.IsUsbOpen = IsUsbOpen;
            if (null != xChip_TopReg) xChip_TopReg.m_open = m_open;
            if (null != xChip_HDR_Ae) xChip_HDR_Ae.m_open = m_open;
            SerialSend.m_open = m_open;
        }

        private void textEdit1_EditValueChanged(object sender, EventArgs e)
        {
            //var ty= Regex.Replace(textEdit1.Text, ".{4}", "$0");
            // textEdit1.Text = ty;
        }

        private void barButtonItem42_ItemClick(object sender, DevExpress.XtraBars.ItemClickEventArgs e)
        {
            binTestForm bintestform = new binTestForm();
            bintestform.StartPosition = FormStartPosition.CenterParent;
            bintestform.ShowDialog();
        }

        private void simpleButton12_Click(object sender, EventArgs e)
        {
            if (GetConfigValue("IsSerial") == "TVE")
            //if (portusbBtn.ImageOptions.ImageUri.Uri.Contains("AlignVerticalLeft"))
            {
                if (!sPortTemp.IsOpen)//串口检测
                {
                    DevExpress.XtraEditors.XtraMessageBox.Show("串口未打开");
                    return;
                }

                var m_nFollowArea0 = SerialSend.ReadRegister(0x200014c0, sPortTemp);
                var m_nFollowArea1 = SerialSend.ReadRegister(0x200014c1, sPortTemp);
                var m_nFollowArea2 = SerialSend.ReadRegister(0x200014c2, sPortTemp);
                var m_nFollowArea3 = SerialSend.ReadRegister(0x200014c3, sPortTemp);
                textEdit3.Text = (m_nFollowArea3 << 24 | m_nFollowArea2 << 16 | m_nFollowArea1 << 8 | m_nFollowArea0).ToString("X8");
            }

            if (GetConfigValue("IsSerial") == "USB" || GetConfigValue("IsI2C") == "1")
            //if (portusbBtn.ImageOptions.ImageUri.Uri.Contains("AlignVerticalRight"))
            {
                if (!IsUsbOpen)
                {
                    DevExpress.XtraEditors.XtraMessageBox.Show("USB未打开");
                    return;
                }
                var m_nFollowArea0 = SerialSend.ReadRegister(0x200014c0, sPortTemp);
                var m_nFollowArea1 = SerialSend.ReadRegister(0x200014c1, sPortTemp);
                var m_nFollowArea2 = SerialSend.ReadRegister(0x200014c2, sPortTemp);
                var m_nFollowArea3 = SerialSend.ReadRegister(0x200014c3, sPortTemp);
                textEdit3.Text = (m_nFollowArea3 << 24 | m_nFollowArea2 << 16 | m_nFollowArea1 << 8 | m_nFollowArea0).ToString("X8");
            }
        }

        private void simpleButton13_Click(object sender, EventArgs e)
        {
            if (null == BinHelp.lspList)
            {
                OpenBinParsing();
            }
            if (null != BinHelp.lspList)
            {
                OpenFileDialog openFileDialog = new OpenFileDialog();//将打开的地址给ofd
                openFileDialog.Filter = "TXT Files(*.txt)|*.txt|All Files(*.*)|*.*";
                if (openFileDialog.ShowDialog() == DialogResult.OK)//用户是否选择确定
                {
                    try
                    {
                        string txt_str = String.Empty;
                        string[] ss;
                        // string line;
                        UInt32 reg_address;
                        UInt32 reg_data;
                        //UInt32 Value;
                        StreamReader f2 = new StreamReader(openFileDialog.FileName, System.Text.Encoding.GetEncoding("gb2312"));//gb2312编码，为制定文件名初始化
                        WaitBefore.Start("文件写", "正在加载中", 60);
                        //SerialSend.isDebug = false;
                        while (f2.Peek() > -1)
                        {
                            try
                            {
                                txt_str = f2.ReadLine().Trim();
                                //ss = txt_str.Split(new char[] { ','}, StringSplitOptions.RemoveEmptyEntries);
                                if (txt_str.Contains("//"))//去除注释
                                {
                                    txt_str = txt_str.Remove(txt_str.IndexOf("//"));
                                }
                                txt_str = txt_str.Replace('，', ',').Replace(" ", "");//全换成英文逗号，去掉空格
                                ss = txt_str.Split(',');
                                if (ss.Length > 2)
                                {
                                    if (ss[0].Trim() == "0xfffd")
                                    {
                                        addr = (Convert.ToUInt32(ss[1].Trim(), 16) & 0xff) << 24;
                                    }
                                    else if (ss[0].Trim() == "0xfffe")
                                    {
                                        //addr = 0x80000000;                                   
                                        addr = (addr & 0xff000000) + ((Convert.ToUInt32(ss[1].Trim(), 16) & 0xff) << 16);
                                    }
                                    else if (ss[0].Trim() == "0xffff")
                                    {
                                        uint t;
                                        t = (Convert.ToUInt32(ss[1].Trim(), 16) & 0xff);
                                        Thread.Sleep(1000);
                                    }

                                    else if (ss[0].Trim() == "0xf4f5")
                                    {
                                        ;
                                    }
                                    else if (ss[0].Trim() == "0xf5f5")
                                    {
                                        ;
                                    }
                                    else if (ss[0].Trim() == "0xf6f5")
                                    {
                                        ;
                                    }
                                    else if (ss[0].Trim() == "0xfff3")
                                    {
                                        UInt16 chip_id;
                                        reg_address = 0x80500010;
                                        reg_data = 0;
                                        fb.ReadRegData(0x11, reg_address, ref reg_data, sPortTemp);
                                        chip_id = (UInt16)(reg_data >> 16);
                                        if (chip_id != Convert.ToUInt32(ss[1].Trim(), 16))
                                        {
                                            f2.Close();//释放系统资源
                                            f2.Dispose();
                                            DevExpress.XtraEditors.XtraMessageBox.Show("Chip ID don't match, Write stopped!");
                                            //MessageBox.Show("Chip ID don't match, Write stopped!");
                                            break;
                                        }

                                    }
                                    else
                                    {

                                        reg_address = addr + (Convert.ToUInt32(ss[0].Trim(), 16) & 0xffff);

                                        reg_data = Convert.ToUInt32(ss[1].Trim(), 16);
                                        //编写Bin更新数据
                                        var temp = SerialSend.ReadRegister(BinHelp.BootSettingIdx, sPortTemp);
                                        BinHelp.SetBinUpdateData(ref BinHelp.BinList, reg_address.ToString("X2"), reg_data.ToString("X"), (uint)temp);
                                        //SerialSend.WriteRegister(reg_address, reg_data, sPortTemp);

                                        Thread.Sleep(5);
                                    }

                                }
                            }
                            catch (Exception ex)
                            {
                                DevExpress.XtraEditors.XtraMessageBox.Show(ex.Message);
                                //MessageBox.Show(ex.Message);
                            }
                        }
                        Application.DoEvents();
                        f2.Close();//释放系统资源
                        f2.Dispose();
                        WaitBefore.Close();
                        SerialSend.isDebug = true;
                        DevExpress.XtraEditors.XtraMessageBox.Show("完成");
                        //MessageBox.Show("完成");
                    }

                    catch (Exception ex)
                    {
                        WaitBefore.Close();
                        SerialSend.isDebug = true;
                        DevExpress.XtraEditors.XtraMessageBox.Show(ex.Message);
                        //MessageBox.Show(ex.Message);
                    }
                }

            }


        }

        private void barButtonItem42_ItemClick_1(object sender, DevExpress.XtraBars.ItemClickEventArgs e)
        {
            if (navigationFrame.Pages.Any(c => c.Caption == "page_TveSizeReckon"))
            {
                //navigationFrame.SelectedPageIndex = navigationFrame.Pages.FindIndex(c => c.Caption == "page_TveSizeReckon");
                navigationFrame.SelectedPage = (INavigationPage)navigationFrame.Pages.FindFirst(c => c.Caption == "page_TveSizeReckon");

                //xChip_DeriveNew.sPortTemp = sPortTemp;
            }
            else
            {
                this.splashScreenManager1.ShowWaitForm();
                NavigationPage page = new NavigationPage();

                xChip_TveSizeReckon = new XChip_TveSizeReckon();
                xChip_TveSizeReckon.Dock = DockStyle.Fill;
                //xChip_AWB.sPortTemp = sPortTemp;
                page.Controls.Add(xChip_TveSizeReckon);
                page.Name = "page_TveSizeReckon";
                navigationFrame.Pages.Add(page);
                navigationFrame.SelectedPage = page;
                this.splashScreenManager1.CloseWaitForm();
            }

        }

        private void barButtonItem2_ItemClick_1(object sender, DevExpress.XtraBars.ItemClickEventArgs e)
        {
            string directoryPath = Application.StartupPath + @"\DB\";
            string wordFilePath = "";
            if (GetConfigValue("IsSerial") == "USB" || GetConfigValue("IsI2C") == "1")
            {
                wordFilePath = Path.Combine(directoryPath, "XChipTool_Usb_ISP3.0芯片调试软件用户手册.doc");
            }
            else
            {
                wordFilePath = Path.Combine(directoryPath, "XChipTool_Tve_ISP3.0芯片调试软件用户手册.docx");
            }
            System.Diagnostics.Process.Start("explorer.exe", wordFilePath);
        }

        private void simpleButton14_Click(object sender, EventArgs e)
        {
            if (GetConfigValue("IsSerial") == "USB" || GetConfigValue("IsI2C") == "1")
            {
                var binlistTempusb = BinHelp.BinList;

                if (null == binlistTempusb || binlistTempusb.Count == 0)
                {
                    DevExpress.XtraEditors.XtraMessageBox.Show("无数据，请先下载！");
                    return;
                }
                SaveFileDialog sfd = new SaveFileDialog();
                //设置文件类型 
                sfd.Filter = "BIN文件（*.bin）|*.bin";
                //设置默认文件类型显示顺序 
                sfd.FilterIndex = 1;
                //保存对话框是否记忆上次打开的目录 
                sfd.RestoreDirectory = true;
                //设置文件名
                sfd.FileName = "XChipNewbin_" + DateTime.Now.ToString("yyyyMMddHHmms");
                var Save_BIN_Output_File_FileName_Path = string.Empty;

                if (sfd.ShowDialog() == DialogResult.OK)
                {
                    Save_BIN_Output_File_FileName_Path = sfd.FileName.ToString();
                    //var hex = AppHelper.StringToUTF8(System.IO.Path.GetFileName(Save_BIN_Output_File_FileName_Path)); 
                    //if (!BinHelp.SetBinNameUpdateData(ref BinHelp.BinList, hex))
                    //{
                    //    DevExpress.XtraEditors.XtraMessageBox.Show("修改bin名称失败请检查");
                    //    return;
                    //}
                    BinHelp.BinOutFile(Save_BIN_Output_File_FileName_Path, binlistTempusb);
                    DevExpress.XtraEditors.XtraMessageBox.Show("导出完成");
                }

            }
            else
            {
                BinHelp.IsPartition = Partition_check.Checked;
                //根据 分段发送测试
                var binlistTemp = BinHelp.GetUpdateIndex();
                if (null == binlistTemp || binlistTemp.Count == 0)
                {
                    DevExpress.XtraEditors.XtraMessageBox.Show("无数据，请先下载！");
                    return;
                }
                SaveFileDialog sfd = new SaveFileDialog();
                //设置文件类型 
                sfd.Filter = "BIN文件（*.bin）|*.bin";
                //设置默认文件类型显示顺序 
                sfd.FilterIndex = 1;
                //保存对话框是否记忆上次打开的目录 
                sfd.RestoreDirectory = true;
                //设置文件名
                sfd.FileName = "XChipNewbin_" + DateTime.Now.ToString("yyyyMMddHHmms");
                var Save_BIN_Output_File_FileName_Path = string.Empty;

                if (sfd.ShowDialog() == DialogResult.OK)
                {
                    Save_BIN_Output_File_FileName_Path = sfd.FileName.ToString();
                    BinHelp.BinOutFile(Save_BIN_Output_File_FileName_Path, binlistTemp);
                    DevExpress.XtraEditors.XtraMessageBox.Show("导出完成");
                }

            }
        }

        private void simpleButton15_Click(object sender, EventArgs e)
        {
            //if (!sPortTemp.IsOpen)//串口检测 
            //{
            //    DevExpress.XtraEditors.XtraMessageBox.Show("串口未打开");
            //    return;
            //}
            //USB是2000f28
            int aaa = 0x20000f28;
            List<byte> hexData = new List<byte>();
            for (int i = aaa; i < aaa + 40; i++)
            {
                hexData.Add((byte)SerialSend.ReadRegister((ulong)i, sPortTemp));
            }
            string asciiString = Encoding.ASCII.GetString(hexData.ToArray());
            DevExpress.XtraEditors.XtraMessageBox.Show("当前固件版本:" + asciiString);
        }


        /// <summary>
        /// 用来测试AE get的方法和打开关闭串口
        /// </summary>
        private void XChip_AeTest()
        {
            /*
            目标：1. 测试打开关闭USB 串口测试   2.测四AEGet方法测试   
            目的：USB串口Get数据偶尔 还存在掉线问题，图像正常输出但是寄存器无法get需要重新连接USB设备
            步骤： 1.打开USB串口 2.关闭USB串口 3.打开USB串口 4.读取Get ->AE界面寄存器值
            
            */
            var isbool = true;
            int g = 0;

            while (isbool)
            {
                logger.Info($"调用次数 ------->{g}------->");
                try
                {
                    btnUsb_Click(null, null);
                    logger.Info($"测试打开USB串口");
                    if (!IsUsbOpen)
                    {
                        logger.Info($"USB串口未打开重新打开");
                        btnUsb_Click(null, null);
                        logger.Info($"USB串口打开完成");
                    }
                    xChip_AE.GetISPAeSetting();
                    logger.Info($"执行AE Get 方法调用");
                    btnUsb_Click(null, null);
                    logger.Info($"USB串口 关闭");
                    g++;
                }
                catch (Exception)
                {
                    isbool = false;

                }
            }

        }

        private void XChip_AeTest2()
        {
            /*
            
            */

            List<ISPReg> regList = new List<ISPReg>();

            regList.Add(new ISPReg() { addr = 0x20000040, value = 0x0 });
            regList.Add(new ISPReg() { addr = 0x20000064, value = 0x0 });
            regList.Add(new ISPReg() { addr = 0x20000065, value = 0x0 });

            //regList.Add(new ISPReg() { addr = 0x80500020, value = 0x40 });
            regList.Add(new ISPReg() { addr = 0x20000C78, value = 0x40 });
            regList.Add(new ISPReg() { addr = 0x20000C79, value = 0x40 });
            regList.Add(new ISPReg() { addr = 0x20000C7A, value = 0x40 });
            regList.Add(new ISPReg() { addr = 0x20000C7B, value = 0x40 });
            regList.Add(new ISPReg() { addr = 0x20000C7C, value = 0x40 });
            regList.Add(new ISPReg() { addr = 0x20000C7D, value = 0x40 });
            regList.Add(new ISPReg() { addr = 0x20000C7E, value = 0x40 });
            regList.Add(new ISPReg() { addr = 0x20000C7F, value = 0x40 });
            regList.Add(new ISPReg() { addr = 0x20000C80, value = 0x40 });
            regList.Add(new ISPReg() { addr = 0x20000C81, value = 0x40 });
            regList.Add(new ISPReg() { addr = 0x20000C82, value = 0x40 });
            regList.Add(new ISPReg() { addr = 0x20000C83, value = 0x40 });
            regList.Add(new ISPReg() { addr = 0x20000C84, value = 0x40 });
            regList.Add(new ISPReg() { addr = 0x20000C85, value = 0x40 });
            regList.Add(new ISPReg() { addr = 0x20000C86, value = 0x40 });
            regList.Add(new ISPReg() { addr = 0x20000C87, value = 0x40 });
            regList.Add(new ISPReg() { addr = 0x20000C88, value = 0x40 });
            regList.Add(new ISPReg() { addr = 0x20000C89, value = 0x40 });
            regList.Add(new ISPReg() { addr = 0x20000C8A, value = 0x40 });
            regList.Add(new ISPReg() { addr = 0x20000C8B, value = 0x40 });
            regList.Add(new ISPReg() { addr = 0x20000C8C, value = 0x40 });
            regList.Add(new ISPReg() { addr = 0x20000C8D, value = 0x40 });
            regList.Add(new ISPReg() { addr = 0x20000C8E, value = 0x40 });
            regList.Add(new ISPReg() { addr = 0x20000C8F, value = 0x40 });
            regList.Add(new ISPReg() { addr = 0x20000C90, value = 0x40 });
            regList.Add(new ISPReg() { addr = 0x20000C91, value = 0x40 });
            regList.Add(new ISPReg() { addr = 0x20000C92, value = 0x40 });
            regList.Add(new ISPReg() { addr = 0x20000C93, value = 0x40 });

            var isbool = true;
            int g = 0;

            while (isbool)
            {
                logger.Info($"调用次数 ------->{g}------->");
                try
                {
                    g++;
                    foreach (var item in regList)
                    {
                        item.value = (uint)new Random().Next(15);

                        bool issbool;
                        if (IntPtr.Size == 8)
                        {
                            issbool = XChipUSB.UsbRegisterWrite64((uint)item.addr, (uint)item.value, false);
                            SerialSend.Sendser("W:0x" + item.addr.ToString("X2"), item.value.ToString("X2") + ",状态：" + issbool);
                        }
                        //SerialSend.WriteRegister(item.addr, item.value, sPortTemp);
                    }

                    List<ISPReg> regListTemp = new List<ISPReg>();

                    foreach (var item in regList)
                    {
                        uint pVule = 0x0;
                        var issbool = false;
                        if (IntPtr.Size == 8)
                        {
                            issbool = XChipUSB.UsbRegisterRead64(item.addr, ref pVule, true);
                            SerialSend.Sendser("R:0x" + (item.addr).ToString("X2"), pVule.ToString("X2") +",状态："+ issbool);


                        }

                        regListTemp.Add(new ISPReg() { addr = item.addr, value = (uint)pVule });
                    }

                    for (int i = 0; i < regList.Count; i++)
                    {


                        if (regListTemp.Find(c => c.addr == regList[i].addr).value == regList[i].value)
                        {
                            continue;
                        }
                        else
                        {
                            logger.Info($"测试出现错误 原始地址：{regList[i].addr.ToString("X")}原始值:{regList[i].value.ToString("X")}   错误值:{regListTemp.Find(c => c.addr == regList[i].addr).value.ToString("X")}");
                            isbool = false;
                        }
                    }

                }
                catch (Exception ex)
                {
                    logger.Info(ex.Message.ToString());
                    isbool = false;
                }

            }


        }


        private void XChip_RegTest()
        {
            /*
            目标：1. 测试修改寄存器写入读写时间后   是数据是否正常 
            目的：寄存器读写存在一个20毫秒的延迟时间，缩短这个延迟时间到1毫秒，看数据是否正常
            步骤： 1.定义一堆地址数据 2.写入数据 3.读取数据  4.校验数据
            
            */
            List<ISPReg> regList = new List<ISPReg>();

            regList.Add(new ISPReg() { addr = 0x80500050, value = 0x44 });
            regList.Add(new ISPReg() { addr = 0x80500051, value = 0x39 });
            regList.Add(new ISPReg() { addr = 0x80500052, value = 0x82 });
            regList.Add(new ISPReg() { addr = 0x80500053, value = 0x40 });

            //regList.Add(new ISPReg() { addr = 0x80500020, value = 0x40 });
            regList.Add(new ISPReg() { addr = 0x20000108, value = 0x40 });
            regList.Add(new ISPReg() { addr = 0x20000109, value = 0x40 });
            regList.Add(new ISPReg() { addr = 0x2000010a, value = 0x40 });
            regList.Add(new ISPReg() { addr = 0x2000010b, value = 0x40 });
            regList.Add(new ISPReg() { addr = 0x2000010c, value = 0x40 });
            regList.Add(new ISPReg() { addr = 0x2000010d, value = 0x40 });
            regList.Add(new ISPReg() { addr = 0x2000010e, value = 0x40 });
            regList.Add(new ISPReg() { addr = 0x2000010f, value = 0x40 });
            regList.Add(new ISPReg() { addr = 0x20000110, value = 0x40 });
            regList.Add(new ISPReg() { addr = 0x20000111, value = 0x40 });
            regList.Add(new ISPReg() { addr = 0x20000112, value = 0x40 });
            regList.Add(new ISPReg() { addr = 0x20000113, value = 0x40 });
            regList.Add(new ISPReg() { addr = 0x20000114, value = 0x40 });
            regList.Add(new ISPReg() { addr = 0x20000115, value = 0x40 });
            regList.Add(new ISPReg() { addr = 0x20000116, value = 0x40 });
            regList.Add(new ISPReg() { addr = 0x20000117, value = 0x40 });

            var isbool = true;
            int g = 0;

            while (isbool)
            {
                logger.Info($"调用次数 ------->{g}------->");
                try
                {
                    g++;
                    foreach (var item in regList)
                    {
                        item.value = (uint)new Random().Next(15);
                        SerialSend.WriteRegister(item.addr, item.value, sPortTemp);
                    }

                    List<ISPReg> regListTemp = new List<ISPReg>();

                    foreach (var item in regList)
                    {
                        regListTemp.Add(new ISPReg() { addr = item.addr, value = (uint)SerialSend.ReadRegister(item.addr, sPortTemp) });
                    }

                    for (int i = 0; i < regList.Count; i++)
                    {


                        if (regListTemp.Find(c => c.addr == regList[i].addr).value == regList[i].value)
                        {
                            continue;
                        }
                        else
                        {
                            logger.Info($"测试出现错误 原始地址：{regList[i].addr.ToString("X")}原始值:{regList[i].value.ToString("X")}   错误值:{regListTemp.Find(c => c.addr == regList[i].addr).value.ToString("X")}");
                            isbool = false;
                        }
                    }

                }
                catch (Exception ex)
                {
                    logger.Info(ex.Message.ToString());
                    isbool = false;
                }

            }



        }
        private void usbDevice_EditValueChanging(object sender, DevExpress.XtraEditors.Controls.ChangingEventArgs e)
        {
            USBItemIndex = e.NewValue.ToString();
            if (IsUsbOpen && !string.IsNullOrEmpty(e.OldValue.ToString()) && e.NewValue != e.OldValue)
            {
                //DialogResult dr = DevExpress.XtraEditors.XtraMessageBox.Show($"是否需要关闭上一个设备！", "提示", MessageBoxButtons.YesNo, MessageBoxIcon.Asterisk);
                //if (dr == DialogResult.Yes)
                //{
                    setButtonUsbBackColor(btnUsb, false);
                    if (IntPtr.Size == 8)
                    {
                        XChipUSB.UsbUpdateDevice64();
                        //var t = XChipUSB.UsbDestroyUSB64();
                    }
                    else
                    {
                        XChipUSB.UsbUpdateDevice86();
                        //var t = XChipUSB.UsbDestroyUSB86();
                    }
                    IsUsbOpen = false;
                    USBSwitch();
                //}
                return;
            }

        }
        /// <summary>
        /// 关闭软件需要释放USB接口
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void XChipForm_FormClosed(object sender, FormClosedEventArgs e)
        {
            if (GetConfigValue("IsSerial") == "USB")
            {
                if (IntPtr.Size == 8)
                {
                    //XChipUSB.UsbUpdateDevice64();
                    XChipUSB.UsbDestroyUSB64();
                }
                else
                {
                    //XChipUSB.UsbUpdateDevice86();
                    XChipUSB.UsbDestroyUSB86();
                }
            }

        }

        private void barButtonItem43_ItemClick(object sender, DevExpress.XtraBars.ItemClickEventArgs e)
        {
            if (navigationFrame.Pages.Any(c => c.Caption == "page_Flash"))
            {
                //navigationFrame.SelectedPageIndex = navigationFrame.Pages.FindIndex(c => c.Caption == "page_Flash");
                navigationFrame.SelectedPage = (INavigationPage)navigationFrame.Pages.FindFirst(c => c.Caption == "page_Flash");

                xChip_Flash.sPortTemp = sPortTemp;
            }
            else
            {
                this.splashScreenManager1.ShowWaitForm();
                NavigationPage page = new NavigationPage();
                xChip_Flash = XChip_Flash.Instance(sPortTemp);
                xChip_Flash.Dock = DockStyle.Fill;
                //xChip_GAMMA.sPortTemp = sPortTemp;
                page.Controls.Add(xChip_Flash);
                page.Name = "page_Flash";
                navigationFrame.Pages.Add(page);
                navigationFrame.SelectedPage = page;
                this.splashScreenManager1.CloseWaitForm();
            }
            //对USB开关赋值
            USBSwitch();
        }

        private void simpleButton16_Click(object sender, EventArgs e)
        {
            XChip_AEState xchip_ConsReadWin = XChip_AEState.GetInstance(IsUsbOpen);
            XChip_AEState ot = XChip_AEState.GetInstance();
            ot.StartPosition = FormStartPosition.CenterScreen;
            ot.sPortTemp = sPortTemp;
            //ot.ShowDialog();
            ot.m_open = m_open;
            ot.Show();
            ot.Focus();
        }

        private void simpleButton17_Click(object sender, EventArgs e)
        {
            if (GetConfigValue("IsSerial") == "USB" || GetConfigValue("IsI2C") == "1")
            {
                uint pVule = 0x0;
                uint pfps = 0x0;
                var isbool = false;
                if (GetConfigValue("IsI2C") == "1")
                {
                    //pVule = (uint)SerialSend.ReadRegister(BinHelp.CurrentSize, sPortTemp);
                    //pfps = (uint)SerialSend.ReadRegister(0x200065cc, sPortTemp);
                }
                else
                {
                    if (IntPtr.Size == 8)
                    {
                        isbool = XChipUSB.UsbRegisterRead64(BinHelp.CurrentSize, ref pVule, true);
                        isbool = XChipUSB.UsbRegisterRead64(0x200065cc, ref pfps, true);
                        SerialSend.Sendser("R:0x" + (BinHelp.CurrentSize).ToString("X2"), pVule.ToString("X2"));


                    }
                    else
                    {
                        isbool = XChipUSB.UsbRegisterRead86(BinHelp.CurrentSize, ref pVule, true);
                        isbool = XChipUSB.UsbRegisterRead86(0x200065cc, ref pfps, true);
                        SerialSend.Sendser("R:0x" + (BinHelp.CurrentSize).ToString("X2"), pVule.ToString("X2"));
                    }
                }
               
                //200065cc显示当前出图帧率
                var chang = (int)(pVule >> 16); // 使用右移16位操作来获取高16位  
                var kuang = (int)(pVule & 0xFFFF); // 使用位与操作来获取低16位  
                int fps = 0;
                if (pfps != 0)
                {
                    fps = (int)(10000000 / pfps);
                }

                monitorLab.Text = $"{chang} * {kuang} {fps}fps";
            }
            else
            {
                if (!sPortTemp.IsOpen)
                {
                    //DevExpress.XtraEditors.XtraMessageBox.Show("可用端口未打开");
                    return;
                }
                uint temp = (uint)SerialSend.ReadRegister(BinHelp.BootSettingIdx, sPortTemp);
                //var aaa = FlashRead((FlashRead(Convert.ToUInt32("368", 16)) + temp * 4 + 0xd4) + 0x0c);
                if (null != BinHelp.lspList)
                {
                    var lspModel = BinHelp.lspList.Find(c => c.SettingHex == temp);
                    monitorLab.Text = $"{lspModel.tName}-{lspModel.vName}";
                }
            }
        }

        private void simpleButton18_Click(object sender, EventArgs e)
        {
            XChip_TopReg xchip_ConsReadWin = XChip_TopReg.GetInstance(sPortTemp, addressregisterBll);
            XChip_TopReg ot = XChip_TopReg.GetInstance();
            ot.StartPosition = FormStartPosition.CenterScreen;
            ot.sPortTemp = sPortTemp;
            USBSwitch();
            ot.IsUsbOpen = IsUsbOpen;
            //ot.ShowDialog();
            ot.m_open = m_open;
            ot.Show();
            ot.Focus();
        }

        private void btnI2cRefresh_Click(object sender, EventArgs e)
        {
            if (!m_open)
            {
                MessageBox.Show("设备未打开！！！");
                return;
            }
            //devicecombox.Items.Clear(); //添加清空
            //devicecombox2.Items.Clear();//添加清空
            i2cDevice.DataSource = null;
            OpenUSB2I2C("");
            List<string> i2cList = new List<string>();
            string msg = string.Empty;
            for (uint i = 0; i < 0xff; i++)
            {
                uint mwlen = 4; //写长度 a0 00 00 00
                uint mrlen = 1; //读长度
                //byte oByte = 0;
                byte[] wbuffer = new byte[3];
                wbuffer[0] = byte.Parse(i.ToString());
                wbuffer[1] = 0;
                wbuffer[2] = 0;
                mwlen = 3;
                byte[] rbuffer = new byte[1];
                if (USBIOXdll.USBIO_StreamI2C(i2cmIndex, mwlen, wbuffer, mrlen, rbuffer))
                {
                    if (rbuffer[0] != 0xff && (i % 2) == 0)
                    {
                        i2cList.Add(i.ToString("X2"));
                        msg += $"搜索到设备：0x{i.ToString("X2")}\r\n";
                        i2cid = i;
                    }
                    SerialSend.i2cmIndex = i2cmIndex;
                    SerialSend.m_open = m_open;
                    SerialSend.IsI2C = IsI2C;
                    SerialSend.i2cid = i2cid;
                }
            }

            if (string.IsNullOrEmpty(msg))
            {
                MessageBox.Show("未搜索到设备地址！！！");
            }
            else
            {
                MessageBox.Show(msg);
            }
            i2cDevice.DataSource = i2cList;
        }
        delegate void SetTextCallback(string text);
        public void OpenUSB2I2C(string text)
        {
            try
            {
                USBIOXdll.USBIO_CloseDevice(i2cmIndex);
            }
            catch (Exception ex)
            {

                throw;
            }
            
            var mid = USBIOXdll.USBIO_OpenDevice(i2cmIndex);
            if (-1 != (int)mid)
            {
                m_open = true;
                USBSwitch();
            }
            else
            {
                m_open = false;
                USBSwitch();
            }
            if (m_open)
            {
                if (this.link_txt.InvokeRequired)
                {
                    SetTextCallback d = new SetTextCallback(OpenUSB2I2C);
                    this.Invoke(d, new object[] { text });
                }
                else
                {
                    link_txt.Text = "设备已插上";
                }

            }
            else
            {
                if (this.link_txt.InvokeRequired)
                {
                    SetTextCallback d = new SetTextCallback(OpenUSB2I2C);
                    this.Invoke(d, new object[] { text });
                }
                else
                {
                    link_txt.Text = "设备未连接";
                }
            }
        }

        private void button9_Click(object sender, EventArgs e)
        {
            OpenUSB2I2C("");

        }
    }
}